您的位置:首页 > 其它

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: