每日一练之Reverse Integer[LeetCode No.7]-翻转整数
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。
class Solution {
public:
int reverse(int x) {
long long res = 0;
while(x) {
res = res*10 + x%10;
x /= 10;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res;
}
};