Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这个题比较简单,考虑特殊情况如12000,注意检查反转后数字是否会越界溢出。代码如下:
class Solution { public: int reverse(int x) { bool minus = false; short int splitNum[10]; int i = 0, j = 0; unsigned int num, result = 0; unsigned int MAX = 2147483647; unsigned int MIN = 2147483648; if(x < 0) { num = 0 - x; minus = true; } else { num = x; } while(num != 0) { splitNum[i++] = num%10; num = num/10; } while(splitNum[j] == 0) j++; while(j < i) { if(!minus && (MAX-splitNum[j])/10 >= result) { result = result*10 + splitNum[j]; j++; } else if(minus && (MIN-splitNum[j])/10 >= result) { result = result*10 + splitNum[j]; j++; } else { return 0; } } return minus ? (0-result) : result; } };
leetcode——Reverse Integer 反转整数数字(AC),布布扣,bubuko.com
leetcode——Reverse Integer 反转整数数字(AC)
原文地址:http://blog.csdn.net/dalongyes/article/details/28984413