2013.12.1 22:24
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.
Solution:
Basic solution for this problem is to compare the digits at both ends of the number one by one, until all pairs are determined equal.
Here are the special cases I've come up with:
1. 0 is of course a palindrome.
2. INT_MIN and INT_MAX, boundary values can be tricky.
3. negative numbers like -121?
Actually the first two case needs special treatment, as they won't work with the code below. The third case cost me 1WA to find out that -121 is not considered a palindrome by LeetCode OJ. For other numbers, the following code segment works just fine.
Time complexity is O(lg(n)), space complexity is O(1).
Accepted code:
1 // 1RE, 1WA, 1AC must be more careful 2 class Solution { 3 public: 4 bool isPalindrome(int x) { 5 // 1RE here, ignored the case of INT_MIN 6 if(x == INT_MAX || x == INT_MIN){ 7 return false; 8 } 9 10 // IMPORTANT: Please reset any member data you declared, as 11 // the same Solution instance will be reused for each test case. 12 int high, low; 13 14 if(x < 0){ 15 // 1WA here, seems negative number is not palindrome, that's unfair.. 16 return false; 17 } 18 19 if(x == 0){ 20 return true; 21 } 22 23 high = low = 1; 24 while(x / high >= 10){ 25 high *= 10; 26 } 27 28 while(high > low){ 29 if(x / high % 10 != x / low % 10){ 30 return false; 31 }else{ 32 // fixed, didn't cause a WA, lucky.. 33 high /= 10; 34 low *= 10; 35 } 36 } 37 38 return true; 39 } 40 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)