算法#23--整数反转

来源:互联网 发布:运动仿真软件哪个好 编辑:程序博客网 时间:2024/05/01 07:30

Reverse digits of an integer.

Example1: x = 123, return 321Example2: x = -123, return -321Example3: x = -12300, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My code:

public static int Reverse(int x)        {            string s = x.ToString();            char[] arr = s.ToArray();            int start, end = s.Length;            if (x == 0)            {                return 0;            }            start = (x > 0) ? 0 : 1;            for (int i = arr.Length - 1; i >= 0; i--)            {                if (arr[i] != '0')                {                    end = i;                    break;                }            }            char[] data = new char[end - start + 1];            int index = 0;            for (int i = end; i >=start ; i--)            {                data[index++] = arr[i];            }            string buf = new string(data);            int value;            bool successful = int.TryParse(buf, out value);            if (successful)            {                return (x > 0) ? value : -1 * value;            }            else            {                return 0; \\throw new Exception();            }        }

Best code:

public static int Reverse(int x)        {            int result = 0;            while (x != 0)            {                int tail = x % 10;                int newResult = result * 10 + tail;                if ((newResult - tail) / 10 != result)//If overflow exists, the new result will not equal previous one.                {                     return 0;                 }                result = newResult;                x = x / 10;            }            return result;        }
0 0
原创粉丝点击