A realistic, brightly colored interior home-style drawing in blue tones of a software engineer. - Leonardo.ai
Question and Hints:
Given an integer x, return true if x is a palindrome, and false otherwise.
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.
Constraints:
Follow up:
Could you solve it without converting the integer to a string?
First Solution:
💡 先將num轉成文字後切割,再用for loop同時從最前面和最後面檢查,
只要有不同的就回傳false,
若for loop順利跑完,表示符合palindrome,return true.
class Solution {
public boolean isPalindrome(int x) {
String[] num = String.valueOf(x).split("");
for(int i = 0; i < num.length; i++){
int end = num.length-1 - i;
if(end - i > 0){
if(!(num[i].equals(num[end])))
return false;
}
}
return true;
}
}
⏰ Runtime: 29 ms (9.89 %)
📦 Memory: 42 MB (55.87 %)
Upgrade Solution:
think of a math problem.
💡 先設定一些一定不符合迴文的條件:
- 負數
- 大於0且尾數為0
以12321和123321為例,
理論上如果是迴文,從頭到中間值的組成,應該和從尾到中間值的組成一樣,
都是123,1x10x10 + 2x10 + 3,
畫一遍就會很清楚ㄌ,有點像用check從後面往前吃掉一半的感覺。
class Solution {
public boolean isPalindrome(int x) {
if(x<0 || x!=0 && x%10 ==0)
return false;
int check=0;
while(x>check){
check = check*10 + x%10;
x/=10;
}
return (x==check || x==check/10);
}
}
⏰ Runtime: 9 ms (99.32 %)
📦 Memory: 42 MB (65.91 %)