[LeetCode]Reverse Integer

来源:互联网 发布:淘宝店铺免费流量 编辑:程序博客网 时间:2024/06/03 17:04

Description:
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.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

个人拙见:这道题比较简单,只是需要注意几个特殊情况的处理就可以了。以下是两种还不错的解法。

solution1:

public class Solution {    public int reverse(int x) {        int result = 0;        while(x!=0)        {            int temp = x%10;            int newResult = result*10+temp;            //用来判断是否超出int范围            if((newResult-temp)/10!=result){return 0;}            result = newResult;            x /= 10;        }        return result;    }}

solution2

public class Solution {    public int reverse(int x) {        long result = 0;        while(x!=0)        {            long temp = x%10;            result = result*10+temp;            //用来判断是否超出int范围            if(result > Integer.MAX_VALUE){return 0;}            if(result < Integer.MIN_VALUE){return 0;}            x /= 10;        }        return (int)result;    }}
原创粉丝点击