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ù)等于原來的數(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).