---
title: "BinaryCode"
author: "kingfly.good"
date: "2009-08-01T17:22:37Z"
tags: ["C", "C#", "C++", "J#"]
slug: "binarycode"
draft: false
lastmod: "2011-11-08T09:45:26Z"
id: 437623
url: "https://kingfly-good.iteye.com/blog/437623"
---

基础书上的一道题,也记下来吧。
给一个由整数组成的加密字符串，加密方法为：
原字符串中每一个整数与其前一位整数和后一位整数的和，如果其前一位或后一位不存在，则不需加其前一位或后一位.
例如：
若原字符串P为:01111001，则加密后的字符串Q为：12332111
即Q=P+P=0+1=1
Q=P+P+P=0+1+1=2
Q=P+P=0+1=1
现任一给你一个字符串P，求出二进制字符串Q并输出（既Q只能由0,1组成）.若Q不存在则输出"NONE"


```C#

using System;
using System.Collections.Generic;
using System.Text;

namespace BinaryCode
{
    class Program
    {
        static void Main(string[] args)
        {
            string Q = Console.ReadLine();
            string[] Array=decode(Q);
            Console.WriteLine("{0},{1}",Array[0],Array[1]);
            Console.ReadKey();
        }
        public static string[] decode(string Q)
        {
            StringBuilder P = new StringBuilder();
            P.Append('0', Q.Length);
            bool[] IsTrue = new bool[2] { true, true };
            string[] result = new string[2];
            for (int j = 0; j <= 1; j++)
            {
                P[0] = (char)(j + 48);
                for (int i = 0; i < Q.Length - 1; i++)
                {
                    P[i + 1] = (char)(Q[i] - P[i] - (i == 0 ? 0 : P[i - 1]-48) + 48);
                }
                if (Q[q.length - 1] == (Q.Length == 1 ? P[q.length - 1] : (P[q.length - 1] + P[q.length - 2]-48)))
                {
                    for (int i = 0; i < Q.Length; i++)
                    {
                        if (P[i] != '0' && P[i] != '1')
                        {
                            IsTrue[j] = false;
                            break;
                        }
                    }
                }
                else
                {
                    IsTrue[j] = false;
                }
                Console.WriteLine(P.ToString());
                result[j] = (IsTrue[j] == true) ? P.ToString() : "NONE";
            }            
            return result;
        }
    }
}

```


运行结果：
![](/upload/attachment/131265/f9501298-e7eb-393f-8d2f-15ac610c2a52.jpg)