Determine whether an integer is a palindrome. Do this without extra space.
判斷一個數(shù)是否為回文數(shù),不要使用額外的空間
回文數(shù)就是順序和倒敘寫出來是同樣的數(shù)的數(shù)久信,比如121,12321等
My Solution
(Java) Version 1 Time: 195ms:
既然是順序倒序都一樣的話窖杀,那就構(gòu)造倒序的數(shù),如果和前面的數(shù)相等的話入篮,那就是回文數(shù)咯陈瘦,從前往后,最高位的變成新數(shù)的最低位,以此類推
public class Solution {
public boolean isPalindrome(int x) {
if(x<0)return false;
else if(x<10)return true;
int temp,num1=x,num2=0;
while(num1>=1){
temp=num1%10;
num2=num2*10+temp;
num1/=10;
}
if(num2==x)return true;
return false;
}
}
(Java) Version 2 Time: 269ms (By cbmbbz):
和我的做法一致……不過看起來簡潔痊项,就是不知道為什么時間會長這么多
public class Solution {
public boolean isPalindrome(int x) {
if (x<0 || (x!=0 && x%10==0)) return false;
int rev = 0;
while (x>rev){
rev = rev*10 + x%10;
x = x/10;
}
return (x==rev || x==rev/10);
}
}
(Java) Version 3 Time: 183ms (By asser):
似乎用了什么黑魔法……
作者的解釋:
This solution compares the least significant digit with the most significant digit just like you would do with a string, then get rid of those digits and repeat.
Example:
1. x = 3428243
2. d = 1000000
3. (x%10) = 3, also (x/d) = 3, so keep going
4. (x/d)*d = 3000000
5. x - 3000000 = 428243
6. x/10 = 42824
7. d/100 = 10000
Repeat till x = 0 (true) or break if step 3 fails (false)
public class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
int d = 1;
while(x/d>=10) d*=10;
while(x>0){
if(x%10 != x/d) return false;
x = (x-(x/d)*d)/10;
d/=100;
}
return true;
}
}