ITeye博客

BinaryCode

kingfly.good · 2009-08-01 17:22 · ASP.NET · C · C++ · J# · C# · Markdown

基础书上的一道题,也记下来吧。 给一个由整数组成的加密字符串,加密方法为: 原字符串中每一个整数与其前一位整数和后一位整数的和,如果其前一位或后一位不存在,则不需加其前一位或后一位. 例如: 若原字符串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"


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

运行结果:

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。