Leetcode 07 Reverse Integer && 09 Palindrome number

07 Digital Inversion

This question is not difficult. It mainly takes the remainder of the input number and saves the remainder in a new number, and then divides the original number by 10 until the input number is 0. The only thing to pay attention to is to define a new number. It is to define its type as long, otherwise, when the number itself is larger than INT_MAX or INT_MIN, it will cross the boundary, and then it will become a number in a random area, and the purpose of returning 0 will not be achieved. The procedure is as follows:
class Solution {
public:
    int reverse(int x) {
        long result=0;
        while(x!=0){
            result=result*10+x%10;
            x /= 10;
        }
        
       return (result > INT_MAX || result < INT_MIN)? 0 : result;

    }
};
09 Palindrome Judgment
Compared with the previous questions, the question is quite concise and very similar to the 08 question, and the reason why I skip the 08 question in solving the problem is as follows:
1. The situation of question 08 is a bit too much and needs to be reconsidered. Although it is a moderately difficult question compared to 08, too many situations have also caused its difficulty to increase.
2. Questions 09 and 07 are similar in purpose, and their solutions are similar.
Why do you say that the two solutions are similar? You need to understand what a palindrome is. The so-called palindrome is that after inverting the numbers, the result is the same as the input, so the solution is roughly the same as that of question 07.
Just add a judgment statement to it, but some small details need to be paid attention to, see the following program:
class Solution {
public:
    bool isPalindrome (int x) {
         if(x>=INT_MAX||x<=INT_MIN) //Determine whether it exceeds the range
            return false;
        int answer=0,tmp=x;
        while(x!=0){
            answer=answer*10+x%10; //Same calculation statement as question 07
            x/=10;
        }
        if(answer==tmp)
            return true;
        else
            return false;
    }
};
Programs that seem to have no problems fail the test in some cases, mainly because the number cannot be a palindrome when the input is less than 0. Therefore, the condition of x>0 can be added when judging the range of x.
if(x>=INT_MAX||x<=INT_MIN)
            return false;
//change to
if(x<0||x>=INT_MAX||x<=INT_MIN)
            return false;
This will allow the AC to pass all tests successfully.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728951&siteId=291194637