当前位置:网站首页>Force buckle_ Palindrome number

Force buckle_ Palindrome number

2022-07-04 22:11:00 Don't sleep in class

Give you an integer x , If x Is a palindrome integer , return true ; otherwise , return false .

Palindrome number refers to positive order ( From left to right ) Reverse order ( From right to left ) Read all the same integers .

for example ,121 It's palindrome. , and 123 No .

Example 1:

 Input :x = 121
 Output :true

Example 2:

 Input :x = -121
 Output :false
 explain : Read left to right ,  by  -121 .  Read right to left ,  by  121- . So it's not a palindrome number .

Example 3:

 Input :x = 10
 Output :false
 explain : Read right to left ,  by  01 . So it's not a palindrome number .

source : Power button (LeetCode)

Java solution

class Solution {
    
    public boolean isPalindrome(int x) {
    
		if(x<0||(x%10==0&&x!=0)){
    
		// Exclude negative numbers and the last digit is 0 Number of numbers 
            return false;
        }
        int revertedNumber=0;
        while(x>revertedNumber){
    
            revertedNumber=revertedNumber*10+x%10;
            x/=10;
            // Reverse the second half of this number 
        }
        return x==revertedNumber||x==revertedNumber/10;
    }
}

Python solution

class Solution:
    def isPalindrome(self, x: int) -> bool:
        s=str(x)
        l=len(s)
        h=l//2
        return s[:h]==s[-1:-h-1:-1]
        # the last one -1 Indicates flashback output , The first two values represent the range 
原网站

版权声明
本文为[Don't sleep in class]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042138559353.html