Judgment palindrome algorithm

Palindrome correct order (left to right) and read in reverse order (right to left) reading is the same integer.

The digital form such 121,1221,13531 is a palindrome, but the palindrome is not -121,10,25 like.

How to tell if a number is a palindrome? This is a very simple algorithm, the most common implementation is to use a stack or other methods, the sequence of numbers in reverse order, and then determine the number after the reverse is equal to the original number. Obviously, this implementation requires at least n cycles to complete judgment.

Provided herein is a more subtle way, use of the characteristics of the number of palindromic, only loop \ (\ frac {n} { 2} \) times to complete the determination, the code and comments are as follows:

bool isPalindrome(int x)
{
    // 负数的第一位带有负号'-',所以一定不是回文数
    // 长度超过一位的数字,第一位肯定不是 0,因此末尾是 0,则一定不是回文数
    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;
}

Guess you like

Origin www.cnblogs.com/faterazer/p/11230846.html