LeetCode #9 Palindrome Number


Palindrome Number


Link : Palindrome Number
Given an integer x , return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.

Ex 1:

  • Input: x = 121
  • Output: true
  • Explanation: 121 reads as 121 from left to right and from right to left.
  • Ex 2:

  • Input: x = -121
  • Output: false
  • Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
  • Ex 3:

  • Input: x = 10
  • Output: false
  • Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
  • Constraints

  • -2^31 <= x <= 2^31 - 1
  • Java code

    class LC4 {
        public boolean isPalindrome(int x) {
            if(x < 0){
                return false;
            }
    
            String str = String.valueOf(x);
            int fullLength = str.length();
            int halfLength = str.length()/2;
            for(int i = 0; i < halfLength; i++){
                if (str.charAt(i) != str.charAt(fullLength-1-i)){
                    return false;
                }
            }
            return true;
        }
    }
    //
    //class Solution {
    //    public boolean isPalindrome(int x) {
    //        if(x<0){
    //            return false;
    //        }
    //        else{
    //            int tmp = x;
    //            int res=0;
    //            while(tmp>0){
    //                int t = tmp%10;
    //                res = res*10+t;
    //                tmp = tmp/10;
    //            }
    //            return res==x;
    //        }
    //    }
    //}
    

    に答える

  • パリンドロンもPythonで解読した経験がある.
  • ですが、ずっと文字列で解いていて、int型で解くとは思わなかったです.
  • は、まず文字列の半分を検索し、インデックスを使用して比較し、徐々に中間に縮小します.
  • 注釈処理の部分は文字列を交換しない解題コードであり、不思議なことにもたらされる.
  • これは
  • 10に分け続け,残存値を蓄積して比較する方法である.
  • パリン症候群がこのように解決できると嘆いた.