LeetCode Online Judge 题目C# 练习 - Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Discuss: 1.If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
2.Reversed integer overflow.
1 public static int ReverseInteger(int x) 2 { 3 bool is_neg = x < 0; 4 int absx = Math.Abs(x); 5 int ret = 0; 6 7 8 while (absx > 0) 9 { 10 ret = ret * 10 + (absx % 10); 11 absx /= 10; 12 } 13 14 if (is_neg) 15 ret *= -1; 16 17 return ret; 18 }
代码分析:
题目已经说了要跟面试官讨论一下两个问题,10, 100 应该返回什么,我觉得肯定是返回 1 的。 如果整数反转后overflow怎么办,这个能提出来应该能展示你的细心。上面的代码没有处理这种情况的,默认反转后不会overflow的。