LeetCode | Reverse Integer
来源:互联网 发布:国内数据备份厂商 编辑:程序博客网 时间:2024/06/07 00:31
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
若果不考虑边界溢出的话,只是简单的实现reverse功能:public class Solution {public static int reverse(int x) {int num = Math.abs(x);int res = 0;while(num != 0){res = res*10 + num%10;num = num/10;}return x>0?res:-res;}}
而实际要考虑Java中int的取值范围,加上边界溢出检测条件,提示当大于等于溢出边界时输出 0
public class Solution { public int reverse(int x) { if(x == Integer.MIN_VALUE) return 0; //在Java的int范围:[-2147483648, 2147483647] //即 abs(MIN_VALUE) = abs(MAX_VALUE) + 1 int num = Math.abs(x); int res = 0; while(num!=0) { if(res>(Integer.MAX_VALUE-num%10)/10) //边界溢出检查:若if条件满足,继续向下执行res = res*10+num%10 rerun 0; //就会得到res >= MAX_VALUE,即发生了溢出 res = res*10+num%10; num /= 10; //此处注意:Java对 / 运算也是截尾的,123/10 = 129/10 =12 } return x>0?res:-res; }}
0 0
- LeetCode:Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : Reverse Integer
- [LeetCode] Reverse Integer
- Leetcode: Reverse Integer
- LeetCode 7 - Reverse Integer
- leetcode 104: Reverse Integer
- Leetcode : Reverse Integer
- 【leetcode】Reverse Integer
- [LeetCode]Reverse Integer
- LeetCode-Reverse Integer
- [leetcode] Reverse Integer
- LeetCode - Reverse Integer
- leetcode之Reverse Integer
- LeetCode | Reverse Integer
- LeetCode: Reverse Integer
- Leetcode: Reverse Integer
- MATLAB图像处理_傅里叶变换
- 第二章复习总结思维导图
- 01(CodeforcesB水平)CQU新生周末狂欢赛F - Smile House
- linux gcc详解
- 华为机试—回文数判断
- LeetCode | Reverse Integer
- 我经历过的失败的产品和项目(五):没有前途的视频呼叫中心
- javascript 鼠标滚动事件绑定事件的方法与注意事项
- 第十七周项目四(1):日期结构体
- 分布式系统阅读笔记(七)-----操作系统的支持
- LEETCODE: Merge Sorted Array
- 移动互联网:中国“90后”快让夜总会小姐失业了
- 大牛的博客
- Mysql数据库优化系列(二)------AWK脚本统计数据库性能参数