Determine whether an integer is a palindrome. Do this without extra space.
判斷一個數是否是迴文,首先的想法是將這個數字轉變成string建立首尾指針進行求解,但考慮到題目要求不能有其他空間的要求我們對算法做進一步優化。給定一個數如果是負數絕對不是迴文,如果是正整數,判斷這個數是幾位數,判斷出這個數的位數之後通過除法和取餘運算獲得對稱位數的數字判斷是否相等即可。
public class Solution {
public boolean isPalindrome(int x) {
if (x<0) return false;
int count = 0;
int temp = x;
while (temp>0){ // 確定有幾位數
temp = temp/10;
++count;
}
for (int i=0;i<count/2;i++){
int a =(int)(x/Math.pow(10,count-i-1));
a = a%10;
int b = (int)(x%Math.pow(10,i+1));
b = (int)(b/Math.pow(10,i));
if (a!=b) return false;
}
return true;
}
}
看到網上還有一種解法即,獲得這個數的中間數字之後將這個數分爲前後兩部分,然後逐次對10取餘。
class Solution {
public:
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x < 0) return false;
int div = 1;
while(x/10 >= div){ // get large division
div *= 10;
}
while(x > 9){
int high = x / div; // left digit
int low = x % 10; // right digit
if(high != low){
return false;
}
x = (x % div) / 10; // get number between first and last
div /= 100;
}
return true;
}
};