Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

這道題因爲簡單一直沒有寫下來,今天做了一下,發現了一個容易越界的情況:就是在判斷divisor大小的時候,開始直接算了x/(divisor*10)>0,這樣在一個情況下比如x=1000000001(位數和Integer.MAX_VALUE)相等,在d=100000000(與最大值位數相等,但是如果*10就會越界)時,d*10=1410065408 所以就要做x/divisor >= 10的判斷

    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        int divisor = 1;
        while(x/divisor >= 10) {
            divisor *= 10;
        }
        while (divisor > 0) {
            if (x%10 == x/divisor) {
                x %= divisor;
                x /= 10;
            } else {
                return false;
            }
            divisor /= 100;
        }
        return true;
    }


發佈了172 篇原創文章 · 獲贊 1 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章