首页 > 代码库 > [LeetCode] Palindrome Number [13]
[LeetCode] Palindrome Number [13]
题目
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
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; } };
-----------------------------------------------------------------------------------------------------------------------------------------
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28913069 )
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。