Reverse Integer
2016-06-04 21:18
393 查看
题目描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
正如题目中所提示的,一些边界条件的考虑可以在笔试或面试时为你的代码带来加分的效果,所以题目就算简单,多思考和锻炼也能带来成长。
这个题主要是考虑越界的问题,将一个值取绝对值的时候可以用long来保存,例如,如果是-2147483648,Math.abs(-2147483648)=-2147483648,将int转换成long之后,才能使Math.abs(-2147483648)=2147483648
代码如下:
public class Solution {
public int reverse(int x) {
int a=x>0?1:-1;
long y=x;
y=Math.abs(y);
long num=0;
while(y!=0){
num=num*10+y%10;
if(num>Integer.MAX_VALUE)
return 0;
y=y/10;
}
return (int)(num*a);
}
}
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
正如题目中所提示的,一些边界条件的考虑可以在笔试或面试时为你的代码带来加分的效果,所以题目就算简单,多思考和锻炼也能带来成长。
这个题主要是考虑越界的问题,将一个值取绝对值的时候可以用long来保存,例如,如果是-2147483648,Math.abs(-2147483648)=-2147483648,将int转换成long之后,才能使Math.abs(-2147483648)=2147483648
代码如下:
public class Solution {
public int reverse(int x) {
int a=x>0?1:-1;
long y=x;
y=Math.abs(y);
long num=0;
while(y!=0){
num=num*10+y%10;
if(num>Integer.MAX_VALUE)
return 0;
y=y/10;
}
return (int)(num*a);
}
}
相关文章推荐
- JSP学习
- 动态链接库使用说明
- 求unsafe集合-indeed Tokyo
- 第二次团队冲刺--9
- Java趣味编程(二)
- iOS开发(OC)——iOS原生API实现文件下载
- golan的template包中的eq函数的用法
- mybatis-generator 代码自动生成工具
- smarty 基本介绍及示例
- mybatis 自动生成代码
- Python 华理 教学周
- 最小生成树-Prim算法和Kruskal算法
- Java工具之Myeclipse程序调试
- 第二阶段团队项目冲刺第六天
- shape形状资源&图片选择器&广播接受者(发送短信)&图片选择器
- iOS沙盒机制
- 经典算法之归并排序
- EffectiveC++,实现(2)static_cast,dynamic_cast,const_static,reinterpret_cast
- js读取本地图片进行预览,上传服务器
- springmvc框架精讲及配置——Springmvc总结(一)