LeetCode 7.Reverse Integer
问题描述: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.
这里需要注意32-bit signed integer需要用long型整数,最后需要跟最大最小判断一下。最大最小分别为INT_MAX和INT_MIN。
class Solution {
public:
int reverse(int x) {
long val = 0;
do{
val = val*10 + x%10;
x /= 10;
}while(x);
return ((val>INT_MAX || val<INT_MIN)?0:val);
}
};
LeetCode 9.Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
这道题跟上道题一样,需要注意的是负数不是回文串。
class Solution {
public:
bool isPalindrome(int x) {
int tmp = x;
int res = 0;
do{
res = res*10 + tmp%10;
tmp /= 10;
}while(tmp);
return (x != res || x < 0)?0:1;
}
};