Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Example
Given x = 123
, return 321
Given x = -123
, return -321
解法一:
1 class Solution { 2 public: 3 /* 4 * @param n: the integer to be reversed 5 * @return: the reversed integer 6 */ 7 int reverseInteger(int n) { 8 long ret = 0; 9 10 while (n != 0) { 11 ret = ret * 10 + n % 10; 12 n /= 10; 13 } 14 15 if (ret > INT_MAX || ret < INT_MIN) { 16 return 0; 17 } 18 19 return (int)ret; 20 } 21 };
先用long来计算防止越界,然后再把越界的处理掉。
解法二:
1 class Solution { 2 public: 3 int reverseInteger(int x) { 4 int rst = 0; 5 6 while(x != 0){ 7 int next_rst = rst * 10 + x % 10; 8 x = x / 10; 9 if(next_rst / 10 != rst) { 10 rst = 0; 11 break; 12 } 13 rst = next_rst; 14 } 15 return rst; 16 } 17 };
参考@NineChapter 的代码