Reverse Integer
Reverse digits of an integer. For example: x = 123, return 321.
Example Questions Candidate Might Ask:
- Q: What about negative integers?
- A: For input x = –123, you should return –321.
- Q: What if the integer’s last digit is 0? For example, x = 10, 100, …
- A: Ignore the leading 0 digits of the reversed integer. 10 and 100 are both reversed as 1.
- Q: What if the reversed integer overflows? For example, input x = 1000000003.
- A: In this case, your function should return 0.
Discussion
比较简单,注意细节。容易漏掉判断溢出。
Solution
class Solution {
public:
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
int reverseInteger(int n) {
// Write your code here
int result = 0;
while(n!=0) {
if(abs(result) > INT_MAX/10) return 0;//判断溢出
result = result*10 + n%10;
n /=10;
}
return result;
}
};
int reverseInteger(int n) {
long long result = 0;
unsigned int temp = abs(n);
while (temp > 0) {
result *= 10;
result += temp % 10;
temp /= 10;
}
result = (n >= 0) ? result : -result;
result = (result > INT_MAX || result < INT_MIN) ? 0 : result;
return result;
}