Likou Question of the Day: Palindrome Algorithm

Question: Given an integer x, if x is a palindrome, return true; otherwise, return false. A palindrome is an integer that reads the same in forward order (left to right) and reverse order (right to left). For example, 121 is a palindrome, but 123 is not.

Example 1:

Input: x = 121

output: true

Example 2:

Input: x=-121

output: false

Example 3:

Input: x=10

output: false

 bool isPalindrome(int x){
    
    
        if(x < 0 || (x % 10 ==0 && x != 0)){
    
    
            return false;
        }
        int revertedNumber = 0;
        while(x > revertedNumber){
    
    
            revertedNumber = revertedNumber * 10 + x % 10;
            x /=10;
        }
        return x == revertedNumber || x == revertedNumber/10;
}

Code idea:

Call parameter x, if x is less than 0, return false, not a palindrome value, if the last digit of x value is 0, or x is equal to 0, return false, not a palindrome value, define reverteNumber as 0, when x is greater than 0 When the value of 12321 is divided by 10, the remainder is 1, and the division of x by 10 is equal to 1232, and the cycle continues.
insert image description here

Guess you like

Origin blog.csdn.net/A6_107/article/details/122503142