LeetCode 第 9 題(Palindrome Number)

liyuanbhu發表於2016-04-18

LeetCode 第 9 題(Palindrome Number)

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.

這道題很簡單,可以利用第 7 題的部分程式碼。 第 7 題將一個整數的各個十進位制位翻轉了。如果翻轉之後數字沒有變化就說明是個 palindrome。

而且我們也不用考慮所謂的整數溢位問題,因為發生溢位的數肯定不是 palindrome。因此,就有了下面的程式碼。

bool isPalindrome(int x)
{
   if(x < 0) return false;
   int ret = 0, xx = x;
    do
    {
        ret = 10 * ret + xx % 10;
        xx = xx / 10;
    }while(xx);
    return ret == x;
}

相關文章