[LeetCode]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.

判斷迴文數字,只要能把這個數字反轉過來,結果和原值相等,就說明這是個迴文數字了。不過需要注意負數不是迴文數字,

因爲前後不對稱(多了-號)。於是這道題就像提示裏所說的一樣,可以用之前做過的Reverse Integer這道題的方法來AC。

但需要注意溢出問題,因爲原值是int型,因此爲了方便,需要long long來解決問題了~

代碼如下,歡迎各位大牛指導交流~

AC,Runtime: 272 ms

//LeetCode_Palindrome Number
//Written by zhou
//2013.11.13
class Solution {
public:
    bool isPalindrome(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        if (x < 0)
           return false;
        
        long long reverse = 0;
        int y = x;
        int temp = 0;
        while (y != 0)
        {
            temp = y % 10;
            reverse = reverse * 10 + temp;
            y = y / 10;
        }
        if ((long long)x == reverse)
           return true;
        else return false;
        
    }
};


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章