LeetCodeOJ. Palindrome Number

試題請參見: https://oj.leetcode.com/problems/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.

解題思路

正如題目中的提示所述, 我們可以把這個問題簡化爲: 比較一個數和這個數的"倒序"是否相等.

不過需要注意一點: 數據溢出的問題, 比如2147483647倒序爲7463847412, 此時超過了INT_MAX的範圍.

不過, 這是沒有關係的, 因爲2147447412是INT_MAX中最大的迴文數了, 這個數並沒有溢出, 因此, 我們可以不需要處理溢出的問題.

源代碼

class Solution {
public:
    bool isPalindrome(int x) {
        return ( x >= 0 && x == reverse(x) );
    }
private:
    int reverse(int x) {
        int y = 0;

        while ( x != 0 ) {
            y = y * 10 + x % 10;
            x /= 10;
        }

        return y;
    }
};


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