日期:2014-05-17  浏览次数:20817 次

(C#)数字反转
/*数字反转,如 12345->54321
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static int ReverseInt(int intToBeReversed)
        {
            int num = intToBeReversed;
            if (num == 0)
                return 0;
            bool flag = false;
            if (num < 0)
            {
                num = 0 - num;
                flag = true;
            }

            int a, b, result = 0;
            int tmp = 0;
            while (num > 0)
            {
                a = num / 10;
                b = num - a * 10;
                tmp = result;
                result *= 10;

                if (result < tmp)
                {
                    throw new System.ArgumentOutOfRangeException("intToBeReversed=" + intToBeReversed);
                }

                tmp = result;
                result += b;

                if (result < tmp)
                {
                    throw new System.ArgumentOutOfRangeException("intToBeReversed=" + intToBeReversed);
                }
                num = a;
            }

            if (flag)
            {
                return 0 - result;
            }
            else
            {
                return result;
            }
        }

        // just for test
        static long M(int num, int a)
        {
            long result = 1L;
            for (; a > 0; a--)
            {
                result *= num;
            }
            Console.WriteLine(result);
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(ReverseInt(12345));
            Console.WriteLine(ReverseInt(123400));
            Console.WriteLine(ReverseInt(0));
            Console.WriteLine(ReverseInt(-123456));
            Console.WriteLine(ReverseInt(1000000002));
            Console.WriteLine(ReverseInt(1000000003));//exception
            Console.WriteLine(ReverseInt((int)M(2, 31) - 1));//exception
        }
    }
}