[Day4]9. Palindrome Number

2017-02-02  本文已影响0人  Shira0905

So far, all the problem I choose to solve is EASY level, which also means that, I am LAZY girl...So, today I am going to choose ---a easy level problem, again...

DESCRIPTION:
Determine whether an integer is a palindrome. Do this without extra space.

ANALYSIS:
My idea is to transform the Integer to String, so that I can use charAt(). Then the problem is very simple. However, this method seems a little informal...
The top solution takes almost as much time as mine (201 ms VS 203 ms). It looks more pretty.

SOLUTIONS:
public static boolean isPalindrome(int x) {
String xx=String.valueOf(x);
for(int i=0;i<xx.length()/2;i++){
if(xx.charAt(i)!=xx.charAt(xx.length()-1-i))
return false;
}
return true;
}

public static boolean isPalindromeTop(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);
}
上一篇下一篇

猜你喜欢

热点阅读