【leetcode】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.
题解:
首先,负数不算回文的整数。
每次比较头尾两个元素是否相等,如果不想等,返回false,如果相等,继续比较下一组,直到头尾相遇。
这里用模10的方法获得整数的最后一位数,用除法获得整数的第一位数,并在比较完这两个数后将头尾的两个数都去掉。例如12321的比较过程如下:
1和1比较,12321->232;
2和2比较,232->3;
3和3比较,3->0 结束。
代码如下:
1 public class Solution { 2 public boolean isPalindrome(int x) { 3 if(x < 0) 4 return false; 5 long div = 1; 6 while(x / div > 0) 7 div *= 10; 8 9 div = div / 10; 10 while(x > 0){ 11 int first = x/(int)div; 12 int last = x%10; 13 if(first != last) 14 return false; 15 x = x % (int)div; 16 x = x/10; 17 div /= 100; 18 19 } 20 return true; 21 } 22 }
要注意的一点就是虽然x是int型,但是第6,7行的循环可能让div超过int型的界,所以将div定义为long型。还有一种方法是在x>=10的时候就跳出循环,div始终比x小,就不会越界了。
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了