Palindrome judge - Algorithm

Palindrome judge

Problem Description

Determine whether an integer is a palindrome. Palindrome correct order (from left to right) and reverse (right to left) reading is the same integer.

示例 1:

Input: 121
Output: true
示例 2:

Input: -121
Output: false
explanation: read from left to right, as -121. Reading from right to left, as 121-. So it is not a palindrome number.
示例 3:

Input: 10
Output: false
interpretation: reading from right to left, to 01. So it is not a palindrome number.
Advanced:

You can not be a string Integer to do to solve this problem?

数反转比对

problem analysis

This question before and 特殊回文数have very similar to the same, but this is not an output, but the judge, the same numbers will be split, but the numbers do not know the exact size of the length, it is necessary to consider the question of the length of the unknown, you can considering the number of new restructuring split number, the new number will be compared with the original number.

Code

class Solution {
public:
    bool isPalindrome(int x) {
        long y=0,xx=x;
        if(x<0)
            return false;
        while(x){
            y*=10;
            y+=x%10;
            x/=10;
        }
        if(y==xx)
            return true;
        else
            return false;
    }
};

operation result

输入

121

输出

true

数学解法

problem analysis

The number is removed from the middle to the ends, respectively, for comparison, if there is a set are not equal, returns false, for the same number of odd bit benefit from
Example 1:
X=52425Here Insert Picture Description
Here Insert Picture Description
Last 4 can be simultaneously on both sides as the number, this number is a palindrome

Example 2:
X=21042
Here Insert Picture Description
Here Insert Picture Description
about several split ends out here appears not equal, it can be returned directlyfalse

Code

class Solution {
public:
    bool isPalindrome(int x) {
        //负数直接排除
        if(x<0)
            return false;
        int y=1;
        while(x / y >= 10) //=10是为了避免10000类似的存在
            y *= 10;//扩大一位,加0
        while(x){
            int left=x/y;//左数
            int right=x%10;//右数
            if(left!=right)
                return false;
            x = (x % y) / 10;//掐头去尾
            y /= 100;//原数减去两位数,则y也缩小两位数
        }
        return true;
    }
};

operation result

输入

121

输出

true

to sum up

This mathematical way, the method of the number of split ends at the same time, also avoids convert a number to a string

Published 59 original articles · won praise 5 · Views 5056

Guess you like

Origin blog.csdn.net/qq_38496329/article/details/104083836