日期:20180912
题目描述:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
详解:
新开了一个数组,把每一位存起来,思路很简单,代码如下:
class Solution {
public:
bool isPalindrome(int x) {
int a[10];
bool isneg = false,res = true;
if(x<0){
return false;
}
int i = 0;
for(;x!=0;i++){
a[i] = x%10;
x /= 10;
}
int j = 0;
i--;
while(j<i){
if(a[j]!=a[i]){
res = false;
}
j++;
i--;
}
return res;
}
};
最后我的用时256ms,最靠前的代码112ms,那究竟是怎么实现的呢。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
{
return false;
}
int test = x;
int reverse = 0;
while(test)
{
reverse = test%10 + 10*reverse;
test = test/10;
}
return reverse == x;
}
};
新建了一个变量,通过循环,让它等于x的反转,然后判断它和x是不是相等。我怎么就没想到,一定是因为我一边喝酒一边写代码。