`
kingfly.good
  • 浏览: 27138 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

BinaryCode

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

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;
        }
    }
}


运行结果:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics