美文网首页
9. Palindrome Number

9. Palindrome Number

作者: weego | 来源:发表于2018-04-03 21:16 被阅读0次

Description

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

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

Solution

判定一个整数是否是回文数,不要尝试调用itoa转化成是否回文字符串来解决,借鉴7. Reverse Integer整型翻转的方法,转化成判定翻转数是否和原数相等

bool isPalindrome(int x) {
    if (x < 0 || x > INT_MAX) {
        return false;
    }
    int number = 0, orign = x;
    while (x) {
        number = number * 10 + x % 10;
        x /= 10;
    }
    return orign == number;
}

相关文章

网友评论

      本文标题:9. Palindrome Number

      本文链接:https://www.haomeiwen.com/subject/wzachftx.html