标签:面试 leetcode algorithm palindrome number
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
判断一个int型整数是不是回文数字,这个题也不难,依次取得数字最高位和最低位进行比较,就可以判断是不是回文数字。需要注意的是负数不是回文数字。
class Solution { public: bool isPalindrome(int x) { if(x<0) return false; int times = 1; int p = x; while(p>=10){ p /= 10; times *= 10; } int low = 0, high = 0; while(x!=0){ low = x%10; high = x/times; if(low != high) return false; x = x%times; x /= 10; times /= 100; } return true; } };
代码二
思路相同,不同算法,明显代码一要简洁很多
class Solution { public: bool isPalindrome(int x) { if(x==0x80000000 || x<0) return false; if(x<0) x= -x; if(-9<=x && x<=9) return true; int n=0; int copy = x; while(copy != 0){ ++n; copy /= 10; } copy = x; int i=n-1; while(i>=n/2){ int h = nIndex(i); int high = x/h; int low = copy%10; if(high!=low) return false; x %= h; copy /= 10; --i; } return true; } int nIndex(int n){ int temp =1; for(int i=0; i<n; i++) temp *= 10; return temp; } };
[LeetCode] Palindrome Number [13],布布扣,bubuko.com
[LeetCode] Palindrome Number [13]
标签:面试 leetcode algorithm palindrome number
原文地址:http://blog.csdn.net/swagle/article/details/28913069