描述
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
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?
思路
對於這種簡單的逆序問題,將輸入轉化為StringBuffer
物件,再呼叫逆置函式即可。
但是題目要求不能轉換為字串,所以要從整型下手。
- 當數字為負數時,是肯定不滿足要求的。
- 當數字為正數或0時,只要保證每位數字從高到低的權重*數字之和,等於每位數字從低到高的權重*數字之和,說明這個正數是對稱的。
class Solution {
public boolean isPalindrome(int x) {
boolean flag = true;
if(x < 0){
flag = false;
}
//數字逆置過程
int temp = x, out = 0;
while(temp != 0){
out = out * 10 + temp % 10;
temp = temp / 10;
}
if(x != out){
flag = false;
}
return flag;
}
}複製程式碼
Runtime: 7 ms, faster than 80.18% of Java online submissions for Palindrome Number.
Memory Usage: 40.5 MB, less than 5.02% of Java online submissions for Palindrome Number.