Determine whether an integer is a palindrome. Do this without extra space.
判定一個(gè)整數(shù)是不是回文的,不要使用額外的臨時(shí)空間。
解:
需要想到的幾點(diǎn):負(fù)數(shù)是不是回文如-1,如果想要轉(zhuǎn)化為字符串,用字符串的倒置函數(shù),要想到不能使用額外的臨時(shí)空間。你也可以倒置這個(gè)數(shù),但是要考慮數(shù)字有可能溢出,如果這個(gè)數(shù)溢出的話,必然不是回文數(shù)了,因?yàn)榛匚臄?shù)的倒置之后的數(shù)等于原來(lái)的數(shù)。
采用這種思路:例如1234321利用取余和除數(shù)可以得到兩個(gè)數(shù)1234和123或者另一種情況123321得到兩個(gè)數(shù)123和123,進(jìn)而判斷是不是回文數(shù),參考代碼如下(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); } };
時(shí)間復(fù)雜度為O(n),空間復(fù)雜度為O(1).