Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
主要注意的是溢出问题:如果溢出,则系统只取低32位,会造成结果错误。
int reverse(int x) { int result,sum=0; int b; while(x) { b=x%10; result=sum*10+b; x=x/10; if((result-b)/10!=sum) //判断是否溢出 return 0; sum=result; } if(sum>2147483648) return 0; return sum; }