LeetCode 9. Palindrome Number 迴文數字

LeetCode 9. Palindrome Number

9.Palindrome Number

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.
求出迴文數對比

將數字反轉進行對比。可以參考LeetCode 7

public boolean isPalindrome(int x) {
    if(x < 0){
        return false;
    }
    
    int res = 0;
    int y = x;
    while(y != 0){          
        res = res* 10 + (y % 10);
        y = y/10;
    }
    
    return x==res;
}
數字轉字符串

將數字轉換成字符串,然後使用兩個指針左右進行對比。不過這樣做效率很低。因爲還要考慮數字轉字符串的成本。

        if(x < 0 || x >= Integer.MAX_VALUE){
            return false;
        }
        String s = String.valueOf(x);
        int len = s.length();
        int left = 0;
        int right = len -1;
        while(left < right){
            if(s.charAt(left) != s.charAt(right)){
                return false;
            }  
            left++;
            right--;
        }
        return true;
        
    }
            right--;
        }
        return true;
        
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章