Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
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.
1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 if(x<0) return false; 5 if(x==0) return true; 6 vector<int> v; 7 while(x!=0) 8 { 9 v.push_back(x%10); 10 x=x/10; 11 } 12 int n=v.size(); 13 int left=0; 14 int right=n-1; 15 while(left<right) 16 { 17 if(v[left]!=v[right]) 18 return false; 19 left++; 20 right--; 21 } 22 return true; 23 } 24 };
不使用额外内存的方法:
class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } else if (x / 10 == 0) { //个位数默认为true return true; } else { int a = 0; int b = x; while (x != 0) { a = a * 10 + x % 10; //不断取最后一位 x = x / 10; //取到去除最后一位的新值 } if (a == b) { return true; } else { return false; } } } };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了