【Palindrome Number】cpp
题目:
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.
代码:
class Solution { public: bool isPalindrome(int x) { if (x<0) return false; return x==Solution::reverse(x); } static int reverse(int x) { int ret = 0; while (x) { if ( ret>INT_MAX/10 || ret<INT_MIN/10 ) return 0; ret = ret*10 + x%10; x = x/10; } return ret; } };
tips:
1. 如果是负数,认为不是回文数
2. 如果是非负数,则求这个数的reverse,如果等于其本身就是回文数,否则就不是。
利用的就是reverse integer这道题(http://www.cnblogs.com/xbf9xbf/p/4554684.html)。
====================================
还有一种解法可以不用reverse,有点儿类似求字符串是否是回文的题目(头尾两个指针往中间夹逼)。
class Solution { public: bool isPalindrome(int x) { if (x<0) return false; int d = 1; while ( x/d>=10 ) d = d*10; while ( x>0 ) { int high = x/d; int low = x%10; if (high!=low) return false; x = x%d/10; d = d/100; } return true; } };
对于这道题的整数来说,就是找到给定整数的最大位数-1,即d。
每次从高位取一个数,从低位取一个数;然后,再把高低位都去掉获得新数(x=x%d/10);这样照比上一次的数少了两位,因此还有d=d/100。
===========================================
第二次过这道题,根据题意提示,用reverse的结果判断是否是palindrome number。
class Solution { public: bool isPalindrome(int x) { if ( x<0 ) return false; int rev = Solution::reverse(x); return rev==x; } static int reverse(int x) { vector<int> digits; int sign = x>0 ? 1 : -1; int ret = 0; while ( true ) { int digit = fabs(x%10); if ( INT_MAX/10<ret || (INT_MAX/10==ret && INT_MAX%10<digit) ) { return 0; } ret = ret*10 + digit; x = x/10; if ( fabs(x)==0 ) break; } return ret*sign; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?