Reverse digits of an integer. //反转数字的值
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as10, 100. //字符形式时应考虑
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of1000000003 overflows. How should you handle such cases? //异常情况处理
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
C++:
class Solution {
public:
int reverse(int x) {
int result=0;
while(x)
{
result = result*10 + x%10;
assert(result < INT_MAX && result > INT_MIN);
x = x/10;
}
return result;
}
};
Java:
public int reverse(int x) {
int result=0;
while(x!=0) {
result = result*10 +x%10;
x = x/10;
}
return result;
}