Reverse Integer [Easy]

来源:互联网 发布:dnf喇叭软件源码 编辑:程序博客网 时间:2024/05/16 14:59

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

===========================================Answer===========================================

public class Solution {    public int reverse(int x) {                if(x==Integer.MAX_VALUE||x==Integer.MIN_VALUE) return 0;                if(x<10 && x >-10) return x;                int temp=x;        long returnNumber = 0l;        long i=1L;            if(temp<0) temp=-temp;                while(temp>=10) {           temp=temp/10;           i=i*10;                    }            temp=x;        if(temp<0) temp=-temp;        while(temp>=10) {            int modNum = temp%10;            temp=temp/10;            returnNumber=returnNumber + modNum * i;            i=i/10;                    }                returnNumber=returnNumber +temp;                if(returnNumber>Integer.MAX_VALUE) return 0;                if(x<0 && -returnNumber < Integer.MIN_VALUE) return 0;                if(x<0) return (int)-returnNumber;        else return (int)returnNumber;            }}


0 0
原创粉丝点击