問題:this
Determine whether an integer is a palindrome. Do this without extra space.spa
Some hints:code
Could negative integers be palindromes? (ie, -1)leetcode
If you are thinking of converting the integer to string, note the restriction of using extra space.get
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?string
There is a more generic way of solving this problem.it
【注】問題要求O(1)空間複雜度,負數不是迴文數。io
解決:class
①每次提取頭部和尾部的兩個數,判斷它們是否相等,判斷後去掉頭尾繼續。採用除數和取餘實現。暫時不能查看提交信息!耗時337ms。
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0) return false;
int len = 1;
while(x / len >=10) len *= 10;
while(x > 0){
int head = x / len;//獲取頭部
int tail = x % 10;//獲取尾部
if (head != tail) {
return false;
}else{//去掉頭部和尾部
x = (x % len) / 10;
len /= 100;
}
}
return true;
}
}
進化版:
public class Solution { //206ms
public boolean isPalindrome(int x) {
if(x < 0) return false;
int div = 1;
while(x / div >= 10) div = div * 10; //位數
while(x > 0) {
if(x / div != x % 10) return false;
x = x % div; //去除頭部
x = x / 10; //去除尾部
div = div / 100; //位數減2位
}
return true;
}
}
③ 用tempx保存數字x的頭部,用reverse保存除頭部以外x位數的翻轉,對比整個x的頭尾兩位,以及中間全部位reverse之後是否與不reverse時一致,便可獲得結果。
public class Solution { //207ms
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int tempX = x;
int reverse = 0;
while (tempX >= 10) { //// 當tempX剩下一位數的時候停下來 reverse = reverse * 10 + tempX % 10; //將除了最高位以外的位數翻轉 tempX /= 10; //取得最高位 } return tempX == x % 10 && reverse == x / 10; ////對比整個x的頭尾兩位,以及中間全部位reverse之後是否與不reverse時一致 } }