Leetcode题解-7&9
由于题目比较简单而且两道题思路比较接近,将两道题合起来写
7. Reverse Integer【easy】
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.
9. Palindrome Number【easy】
Determine whether an integer is a palindrome. Do this without extra space.
思路
设题目所给整数为x,用一个初始值为0的变量sum,每次sum乘十加上x除以十的余数,然后将x除以十的商赋值x,不断重复直到x等于0
第7题代码
小细节在于用long来存储新的数来判断是否超出32bit的Int的范围
int reverse(int x) {
long sum = 0;
long min = -2147483648, max = 2147483647;
while(x != 0){
sum = sum * 10 + x % 10;
x = x / 10;
if(sum < min || sum > max) return 0;
}
return sum;
}
第9题代码
小细节在于不用直到x==0才结束循环,因为是判断是否为回文数,所以只要sum>=x的时候就可以进行判断了,其中return (x == sum) || (x == (sum/10))是分别对应该数有偶数个位和奇数个位的情况
bool isPalindrome(int x) {
if(x < 0 || (x != 0 && x % 10==0)) return false;
if(x < 10) return true;
int sum = 0;
while(x > sum){
sum = sum * 10 + x % 10;
x = x / 10;
}
return (x == sum) || (x == (sum / 10));
}