题目链接:
题目:
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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题目分析:
给定一个int 型的整数,输出其反转后的数,比如 -123 到 -321。注意点,输入一定保证了是在int 范围里的,但是反转后的数,不一定保证,所以反转后的数如果不在int 范围里,那就返回 0。
解题思路:
数的反转,就是不断的取最后一位 ( x%10 ),然后作为新的数的第一位 ( ans = ans*10 + x%10),利用一个循环就解决了。
这里的难点主要在于怎么判断超没超int 的范围,所以利用long long 型存下来,然后判断如果不在范围,就输出0,在范围就强制类型转换变为int 型。
AC代码:
class Solution {
public:
int reverse(int x) {
long long ans = 0;
while(x)
{
ans = ans*10+x%10;
x /= 10;
}
int maxVal = (1<<31)-1;
int minVal = (1<<31)*(-1);
if(ans > maxVal || ans < minVal)
return 0;
return (int)ans;
}
};