回文数

题目详情

如果一个数正着读和反着读一样大,则这个数叫做回文数,例如121是回文数,123454321是回文数。

 

现给定一个正整数x,输出一个回文数y,要求y > x,并且组成x的所有数字之和与组成y的所有数字之和相等,以及y > x。

x在10^1000以内,因为数字较大,我们用字符串作为输入和输出。

如果无解,请输出Impossible。如果有多个y,输出最小的那个。

 

例如:

输入919,输出14941

输入1,输出Impossible

 

 class Program
    {
        static void Main(string[] args)
        {
            string str = "919";
            int sum = Sum(str);

            if (str == "1" || str == "0" || str[0] == '-')
            {
                Console.WriteLine("Impossible");
            }

            do
            {
                str = Next(str);

                if (IsHuiWen(str) && Sum(str) == sum)
                {
                    Console.Write(str);
                    break;
                }

            } while (true);

            Console.Read();
        }

        /// <summary>
        /// Sum of each digit in a string.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <returns></returns>
        static int Sum(string str)
        {
            int s = 0;

            int low = 0;

            while (low < str.Length)
            {
                s += str[low++] - '0';
            }

            return s;
        }

        /// <summary>
        /// whether a string is huiwen.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <returns></returns>
        static bool IsHuiWen(string str)
        {
            int low = 0;
            int high = str.Length - 1;

            while (low < high)
            {
                if (str[low++] != str[high--])
                    return false;
            }

            return true;
        }

        /// <summary>
        /// String plus 1.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static string Next(string str)
        {
            char[] cs = new char[str.Length + 1];

            int i = str.Length - 1;
            int j = 0;
            int a = 1;
            int t = 0;

            while (i >= 0)
            {
                t = str[i--] - '0' + a;
                cs[j++] = (t % 10).ToString()[0];
                a = t / 10;
            }

            if (a == 1)
            {
                cs[j] = '1';
            }

            string s = "";

            int high = cs.Length - 1;

            while (high >= 0)
            {
                if (cs[high] == '\0')
                    high--;
                else
                    break;
            }

            while (high >= 0)
            {
                s += cs[high--];
            }

            return s;
        }
    }

 

posted @ 2014-01-08 10:44  记忆的森林  阅读(443)  评论(0编辑  收藏  举报