1. 程式人生 > >LeetCode (30) Palindrome Number (迴文數字)

LeetCode (30) 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.
—— 將數字轉換為字串,我們做過判斷字串是否為迴文的題目的,但是這裡會用到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?
—— 將數字逆轉,判斷逆轉前後是否相同,但是這會出現overflow的問題(沒有做過”Reverse Integer”的題目,也不是很清楚為什麼會溢位。)

本題要求判斷數字是否為迴文,並要求不能利用額外的記憶體空間。本題可以利用類似字串的迴文判斷使用兩個指標進行判斷。當然對一個數字我們無法從前後移動兩個指標,指向不同的數字為,這裡我們可以通過數學運算,每次獲得數字的最高位和最低位的數值。

首先獲得數字的位數,依次通過除以 10*ditalNumber 和 對10取餘分別獲得最高位和最低位的數字,判斷兩數字是否相等。需要注意的是每次得到最高位數需要除去的數字大小的變化。總體來說,程式碼比較簡單。

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        if (x < 10) return true;

        int count = 0;
        int t = x;

        while (t)
        {
            count
++; t = t / 10; } int highNum = pow(10, count - 1); while (highNum > 1) { int high = x / highNum; int low = x % 10; if (high != low) return false; x = x - highNum * high; highNum /= 100; x = x / 10; } return true; } };