Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 Output: true
Example 2:
Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
題目來源:https://leetcode.com/problems/palindrome-number/
先給出自己很一般的算法:
1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 if(x>=0&&x<10) 5 return true; 6 if (x<0 || x / 10 == 0) 7 return false; 8 int countDigit = 0, saveX = x; 9 int* numArray = new int[12]; 10 bool flag = true; 11 while (x>=1) { 12 numArray[countDigit] = x - x / 10 * 10; 13 countDigit++; 14 x = x / 10; 15 } 16 x = saveX; 17 for (int i = 0; i<countDigit; i++) { 18 if (numArray[i] != (int)(x / pow(10, countDigit - i-1)) ){ 19 flag = false; 20 break; 21 } 22 else { 23 x = x - numArray[i] * pow(10, countDigit - i-1); 24 } 25 } 26 return flag; 27 } 28 };
照例,發現了一個印度小哥的代碼很簡短:https://leetcode.com/problems/palindrome-number/discuss/5165/An-easy-c%2B%2B-8-lines-code-(only-reversing-till-half-and-then-compare)
1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 if(x<0|| (x!=0 &&x%10==0)) return false; 5 int sum=0; 6 while(x>sum) 7 { 8 sum = sum*10+x%10; 9 x = x/10; 10 } 11 return (x==sum)||(x==sum/10); 12 } 13 };
其實從算法思想上來說,這種思想我也曾想過:把原有數字逆轉,然后比較兩數字是否相同。但是由於int的限制,很可能會發生正向的數字沒有溢出,但是反向的數字就溢出的情況(例如:2147483647,調轉過來就溢出了)。而由我上一篇文章中所說(https://www.cnblogs.com/jiading/p/10422265.html),Int溢出后會不斷減去或者加上4294967296直至整數范圍落在-2147483648 ~ 2147483647內,所以如果直接調轉過來可能會導致整數數值的變化,從而導致比較的不正確,所以我沒有采用這種辦法,而是把整數先一位一位存在數組中,然后一位一位比較,但是這樣涉及到比較的次數就較多,而且還使用了數組作為輔助內存。
而這位小哥的思路就很有價值:他沒有把整個數翻轉過來,而是只翻轉了一半(利用條件:x>sum),所以出while循環時的可能性只有兩種:1.x與sum同位數,但是sum>=x(原整數是偶數位情況) 2.sum比x高一位(原整數是奇數位情況)
而這也導致了最終判斷條件是兩個((x==sum)||(x==sum/10)
利用翻轉一半的方法,就徹底規避了整數超出范圍的情況,非常的機智。