[LeetCode]Palindrome Number解析

鏈接https://leetcode.com/problems/palindrome-number/#/description
難度:Easy
題目:9.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.
翻譯:確定一個整數是否是回文數。不能使用額外的空間。
一些提示:
負數能不能是回文數呢?(比如,-1)
如果你想將整數轉換成字符串,但要注意限制使用額外的空間。
你也可以考慮翻轉一個整數。
然而,如果你已經解決了問題"翻轉整數",
那么你應該知道翻轉的整數可能會造成溢出。
你將如何處理這種情況?
這是一個解決該問題更通用的方法。
思路:什么是回文?指的是“對稱”的數,即將這個數的數字按相反的順序重新排列后,所得到的數和原來的數一樣。
這道題可以看成要計算一個數字是否是回文數字,我們其實就是將這個數字除以10,保留他的余數,下次將余數乘以10,加上這個數字再除以10的余數。依此類推,看能否得到原來的數。
注:負數不是回文數字,0是回文數字.
參考代碼
Java

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) return false;
        int r = 0;
        while (x > r) {
            r = r * 10 + x % 10;
            x = x /10;
        }
        return x == r || x == r / 10;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容