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.
代码:
class Solution {
public:
int reverse(int x) {
long y=0;
while(x){
y*=10;
y+=x%10;
x/=10;
}
if(y>pow(2,31)-1 || y<-1*pow(2,31))
return 0;
return (int)y;
}
};
总结:这题应该是目前最简单的一题了。
long在32位机是4字节,在64位机是8字节。
pow函数的返回值是double型。
居然运行时间0ms,哈哈 =)