Determine whether an integer is a palindrome. Do this without extra space.
判定一個整數是不是回文的,不要使用額外的臨時空間。
解:
需要想到的幾點:負數是不是回文如-1,如果想要轉化為字符串,用字符串的倒置函數,要想到不能使用額外的臨時空間。你也可以倒置這個數,但是要考慮數字有可能溢出,如果這個數溢出的話,必然不是回文數了,因為回文數的倒置之后的數等于原來的數。
采用這種思路:例如1234321
利用取余和除數可以得到兩個數1234
和123
或者另一種情況123321
得到兩個數123
和123
,進而判斷是不是回文數,參考代碼如下(C++):
class Solution { public: bool isPalindrome(int x) { if(x<0) return false; if(x<10) return true; if(x%10==0) return false; if(x<100&&x%11==0) return true; if(x<1000&&((x/100)*10+x%10)%11==0) return true; int res = 0; while(x>res){ res = res*10 + x%10; x = x/10; } return (x==res || x==res/10); } };
時間復雜度為O(n),空間復雜度為O(1).