LeetCode 7. Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-231 <= x <= 231 - 1
实现思路:
本来想转换成字符串再进行处理,其实这样很麻烦,而且代码冗赘不美观,本题有其他更好的方式去解答,其实最好的办法就是取最低位然后变成最高位即可,每次数值x取最低位的办法就是%10,就算是负数依旧可以,也就直接避免了负数的单独处理,本题需要单独判断反转过来的数是否溢出,最好的办法就算设置最大值MAX=0X7FFFFFFF,如果之前反转过来的部分数值已经大于MAX/10的时候说明之后再加一个数到末位肯定也是溢出的。
AC代码:
class Solution {
public:
int reverse(int x) {
int res=0,MAX=0x7FFFFFFF;
while(x!=0) {
if(abs(res)>MAX/10) return 0;//溢出了
res=res*10+x%10;
x/=10;
}
return res;
}
};