009 Palindrome Number[E]

1 題目描述

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.

難度:Easy

2 題目樣例

3 題意分析

就是判斷迴文數,要求空間複雜度 O(1)

其實溢出用int64_t就好了呀,唉算了我們還是按照出題人的想法來。

4 思路分析

翻轉一個數字很容易,但是正如提示裡面提到的可能會溢出,所以我們可以利用迴文數的性質只翻轉一半,然後判定是否跟另一半相等即可,具體實現直接看代碼就好。

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

最後返回的時候如果輸入的x有偶數位,那麼有x==rev,有奇數位則是x==rev/10。

整體時間複雜度 O(lgn) ,空間複雜度 O(1)

5 後記

很簡單的一道題,不過明明用int64_t就行的(碎碎念

推薦閱讀:

[leetcode algorithms]題目12
1. Two Sum
做ACM演算法用什麼開發工具比較好呢?
[leetcode algorithms]題目4
[leetcode algorithms]題目6

TAG:演算法 | 演算法設計 | LeetCode |