Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
思路:要注意溢出。用以下做法,会溢出。
class Solution { public:int reverse(int x) {int ret = 0;while(x){ret = ret * 10 + x%10;x /= 10;}return ret;} };
改进的做法:
class Solution { public:int reverse(int x) {if (x == INT_MIN) return 0;int ret = 0;int digit;bool pos = x>=0?true:false;x = abs(x); //现在对负数求模编译器不统一,所以转为正数操作while(x){digit = x%10;if (ret > (INT_MAX - digit) / 10) //10*ret+digit > INT_MAXreturn 0;ret = ret * 10 + digit;x /= 10;}if(pos) return ret;else return (-ret);} };