天天看点

leetcode 9. Palindrome Number(C语言,判断是否为回环数)18

贴原题:

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

space.

click to show spoilers.

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.

解析:

  本题就是判断一个数是否为回环,题目中已经给出了提示,只要把一个数翻转之后判断是否与原数相等即可。若相等即是回环数,否则就不是。

贴代码:

bool isPalindrome(int x) {
    if(x>=)
    {
        int y=;//翻转x
        int n=x;//保存原本的x值
        while(x)
        {
            y=y*+x%;//倒序;把x的最低位依次压入y的最低位
            x/=;
        }
        if(n==y)//若一个正整数翻转后和原数相等则回环
        {
            return true;
        }
    }
    return false;
}
           

ps:好几天没更新了,心里很难受。

继续阅读