9.Palindrome Number
【题目】
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.
【思路】
回文數簡單就是左到右,右到左皆相同就是回文數了,
【解法】
☆JAVA
class Solution {
public boolean isPalindrome(int x) {
boolean result = false;
int temp = x;
int after = 0;
if(x<0){return result;}
while(temp != 0){
after = after * 10 + temp % 10;
temp = temp / 10;
}
if(x == after){result = true;}
return result;
}
}
☆Python
class Solution:
def isPalindrome(self, x):
boo = False;
result = x;
temp = 0;
if(x<0): return boo;
while(result != 0):
temp = temp * 10 + result % 10;
result = result // 10;
if(temp == x):
boo = True;
return boo;
當然還有之前第七題學到的反轉陣列,這樣可以輕鬆解決這題
class Solution:
def isPalindrome(self, x):
result = str(x)[::-1];
if(str(x) == result):
return True
else:
return False;