【LeetCode算法-7】Reverse Integer
LeetCode第7题:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解题思路:
假如:x=1234,y=0
1)y乘以10,x把末位4移除掉,加给y(x=123,y=4)
2)y乘以10,x把末位3移除掉,加给y(x=12,y=43)
3)y乘以10,x把末位2移除掉,加给y(x=1,y=432)
4)y乘以10,x把末位1移除掉,加给y(x=0,y=4321)
代码:
int y = 0;
while(x/10!=0){
y*=10;
y+=x%10;
x/=10;
}
y=y*10 +x;
结果报错
原因是int的范围是-2147483647~2147483648
leetcode给的input是1534236469,倒转之后是9646324351,导致溢出了。所以要加上溢出判断
最后的代码
class Solution {
public int reverse(int x) {
int negative = 1;
if(x <= Integer.MIN_VALUE)
return 0;
if(x < 0){
x = -x;
negative = -1;
}
long y = 0;
while(x/10!=0){
y*=10;
y+=x%10;
x/=10;
}
y=y*10 +x;
if(y > Integer.MAX_VALUE)
return 0;
else
return (int)y * negative;
}
}
这也是很坑啊,溢出就输出0,鬼知道啊
分类:
刷题
标签:
LeetCode算法
, Reverse Integer
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现