不需要用reverse或者转换成string的方法。每次取头尾两个数比较即可,常数空间,linear time,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPalindrome(int x) { | |
if(x < 0)return false; | |
int div = 1; | |
while(x / div >= 10) | |
div *= 10; | |
while(x) | |
{ | |
int hi = x / div, lo = x % 10; | |
if(hi != lo) | |
return false; | |
x %= div; | |
x /= 10; | |
div /= 100; | |
} | |
return true; | |
} | |
}; |
No comments:
Post a Comment