Leetcode 7 Reverse Integer
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
题意
给出一个32位范围内的整数,返回其反转后的结果,符号保留,如果结果超过范围就返回0。
解题思路
直接一个循环就能解决,要注意判断越界的范围。被坑惨了。。
代码
class Solution {
public:
int reverse(int x) {
long long tmp=x,ans=0;
int flag=0;
if(tmp<0) flag=1,tmp=-tmp;
while(tmp)
{
ans=ans*10+tmp%10;
tmp/=10;
}
long long maxx=(long long)1<<31;
if(ans>maxx-1) return 0;
if(flag) ans=-ans;
return (int)ans;
}
};