标签:string bool back for 通过 ati exp code eth
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?
#include<math.h>
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
if(x>=0&&x<=9)
return true;
int weishu=0;
int temp=x;
while(temp) //先看一下数字总共有几位
{
temp=temp/10;
weishu++;
}
int jishu=0; //看一下是奇数还是偶数
jishu=weishu%2;
int mowei=1;
int shouwei=weishu+1-mowei; //shouwei代表着要和末位对比的位置,而不是真正的首位
if(jishu)
{
while(x&&shouwei!=1){
int a=pow(10,shouwei-1); //这个动作是为了取shouwei,先把后面的位数去了
if((x/a%10)!=(x%10)) //(x/a%10)是shouwei,(x%10)是末位
return false;
x=x/10;
shouwei-=2; //对比完一对,shouwei的位置就减2,因为前面的指针要往后移一位,最后一位抛弃,相当于移了2位
}
}else{ //偶数个位数也一样,区别就是shouwei剩一个还是0个
while(x&&shouwei!=0){
int a=pow(10,shouwei-1);
if((x/a%10)!=(x%10))
return false;
x=x/10;
shouwei-=2;
}
}
return true;
}
};
按要求不转成string来做的。没看题解,我感觉我想的还挺巧妙的,就是提交情况来看,似乎在通过中算比较慢的,但比较省内存。我估计是int转string的方法时间复杂度低。
然后看了题解,发现把数转成回文,然后看是否相等就可以了。瞬间又觉得自己有点蠢。
leetcode9 Palindrome Number(按进阶要求)
标签:string bool back for 通过 ati exp code eth
原文地址:https://www.cnblogs.com/HaoPengZhang/p/11443681.html