9 Palindrome Number 回文數(shù)
Description:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example:
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
題目描述:
判斷一個(gè)整數(shù)是否是回文數(shù)体谒。回文數(shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù)。
示例:
示例 1:
輸入: 121
輸出: true
示例 2:
輸入: -121
輸出: false
解釋: 從左向右讀, 為 -121 丁频。 從右向左讀, 為 121- 。因此它不是一個(gè)回文數(shù)邑贴。
示例 3:
輸入: 10
輸出: false
解釋: 從右向左讀, 為 01 席里。因此它不是一個(gè)回文數(shù)。
進(jìn)階:
你能不將整數(shù)轉(zhuǎn)為字符串來解決這個(gè)問題嗎拢驾?
思路:
- 字符串反轉(zhuǎn)
- 反轉(zhuǎn)一半數(shù)字, 直到反轉(zhuǎn)數(shù)字大于原數(shù)字, 最后一位可以忽略
時(shí)間復(fù)雜度O(lgn), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
// C++ bool型: true/false
bool isPalindrome(int x)
{
if (x < 0 or x % 10 == 0 and x != 0) return false;
int reverse = 0;
while (x > reverse)
{
reverse = reverse * 10 + x % 10;
x /= 10;
}
return x == reverse or x == reverse / 10;
}
};
Java:
class Solution {
public boolean isPalindrome(int x) {
String xString = String.valueOf(x);
String reverse = new StringBuffer(xString).reverse().toString();
return xString.equals(reverse);
}
}
Python:
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]