[leetcode-9-Palindrome Number]

Determine whether an integer is a palindrome. Do this without extra space.

思路:

判断整数是否为回文数。首先负数不行,举例,假如整数为12345,那么它的反转为54321,与原值不相等,返回false。

假如整数为12321,翻转依然为12321,返回true。

bool isPalindrome(int x)
    {
        int newNum = 0;
        int a = 0;
        int temp = x;
        while (x>0)
        {
            a = x % 10;
            newNum = newNum * 10 + a;
            x = x / 10;
        }
        if (newNum == temp) return true;
        else return false;        
    }

其实还有更简便的方法:

那就是提前终止循环,比如12321,第一步转换为1232与1 ,第二步为123与12,再然后是12与123,其实此时已经可以得出结果了。因为123/10 ==12。没必要再计算。

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

参考:

https://discuss.leetcode.com/topic/12820/an-easy-c-8-lines-code-only-reversing-till-half-and-then-compare

原文地址:https://www.cnblogs.com/hellowooorld/p/6663781.html