https://leetcode.com/problems/palindrome-number/
給定一個數字,假如數字從頭到中間和從中間到末端是一樣的
回傳 true,反之回傳 false
範例:
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
進階解題,建議不要用字串型別來解此題
解題答案
我先直接判斷是否為 0 , 是否為負數, 判斷是否為偶數長度, 是否為奇數長度
private boolean test(int x){
String strX = String.valueOf(x);
if (x == 0) {
return true;
}
else if (x < 0) {
return false;
}
else if (strX.length() %2 == 0) {
int quar = (strX.length() / 2);
int bigger = (int)(x / Math.pow(10,quar));
int smaller = (int)(x - (bigger*Math.pow(10,quar)));
String strBigger = String.valueOf(bigger);
String strSmaller = String.valueOf(smaller);
StringBuffer buffer = new StringBuffer(strSmaller);
StringBuffer temp = new StringBuffer();
if (buffer.length() < quar){
for (int i=buffer.length(); i<quar; i++){
temp.append("0");
}
temp.append(buffer);
buffer = temp;
}
strSmaller = buffer.reverse().toString();
if (strBigger.equals(strSmaller)){
return true;
} else {
return false;
}
}
else {
if (strX.substring(0, strX.length()/2).equals(strX.substring(strX.length()/2+1, strX.length()))){
return true;
} else {
return false;
}
}
}
沒有留言:
張貼留言