一 题目
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?
二 分析
easy级别,求数字判断是否是回文。
先按照转成字符串的方式去处理。
public boolean isPalindrome(int x) {
String s = x+"";
String res ="";
for(int i=0;i< s.length();i++ ){
res = res+ s.charAt(s.length()-i-1);
}
if(s.equals(res)){
return true;
}else{
return false;
}
}
Runtime: 12 ms, faster than 10.37% of Java online submissions forPalindrome Number.
Memory Usage: 36.3 MB, less than 5.02% of Java online submissions forPalindrome Number.
如果改用数字的求余方式。
public boolean isPalindrome(int x) {
if(x<0) return false;
int y= x;
Long res=0L;
while (x != 0) {
res = res*10+ x%10;
x= x/10;
if(res> Integer.MAX_VALUE|| res<Integer.MIN_VALUE ){
res =0L;
}
}
if(y==res){
return true;
}else{
return false;
}
}
Runtime: 8 ms, faster than 40.41% of Java online submissions forPalindrome Number.
Memory Usage: 35.9 MB, less than 5.02% of Java online submissions forPalindrome Number.
拆成数组,判断一半的长度
public boolean isPalindrome(int x) {
if(x<0) return false;
String s = x+"";
char[] chars =s.toCharArray();
int n = chars.length;
for(int i=0;i< n/2;i++){
if(chars[i]!=chars[n-1-i] ){
return false;
}
}
return true;
}
Runtime: 8 ms, faster than 40.41% of Java online submissions forPalindrome Number.
Memory Usage: 35.8 MB, less than 5.02% of Java online submissions forPalindrome Number.
我猜测那些快的又得啥位操作之类的吧。
明天再看看吧。。。。。
今天补上,官网也是用了取模的方式,不过更巧妙的是做了一半的判断,比如1221,取模为12,跟剩下的x=12 进行比较。
public class Solution {
public bool IsPalindrome(int x) {
// Special cases:
// As discussed above, when x < 0, x is not a palindrome.
// Also if the last digit of the number is 0, in order to be a palindrome,
// the first digit of the number also needs to be 0.
// Only 0 satisfy this property.
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
// since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber || x == revertedNumber/10;
}
}
Runtime: 6 ms, faster than 100.00% of Java online submissions forPalindrome Number.
Memory Usage: 35.6 MB, less than 7.82% of Java online submissions forPalindrome Number.
Complexity Analysis
-
Time complexity : O(log10(n)). We divided the input by 10 for every iteration, so the time complexity is O(log10(n))
-
Space complexity : O(1).