9. Palindrome Number(easy)

迴文數字判斷,要求:

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.

一般情況下,先試試Reverse Integer(儘管題目不建議這樣做)

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

發現效率不高,回頭看了看,沒什麼問題(對於反轉數字而言)

我沒有第一時間去想那個「more generic way」,先看看能不能優化,想了想應該是循環有點冗餘,對於迴文數字而言,不用完全反轉,只需一半。

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

在gcc 4.8.1下面通過了,但是在leetcode上return x==turn_x || x==(turn_x/10)這一句運行不正常

寫完感覺可能這就是那個「more generic way」吧

推薦閱讀:

6. ZigZag Conversion(medium) & 7.Reverse Integer(easy)
好好玩的螺旋演算法No.69

TAG:LeetCode | 演算法 |