7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

给定一个32位有符号整数,将整数的每位反转,如下:

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321 

Example 3:

Input: 120
Output: 21

注意:
假设翻转后超出32位有符号数的范围(溢出),那么返回0.

大神代码bitzhuwei

public int reverse(int x)
{
    int result = 0;

    while (x != 0)
    {
        int tail = x % 10;
        int newResult = result * 10 + tail;
        if ((newResult - tail) / 10 != result)
        { return 0; }
        result = newResult;
        x = x / 10;
    }

    return result;
}

我的代码(主要难点在于溢出的判定)

class Solution {
public int reverse(int x) {
int result=0;
double temp=0;
int sum=0;
int length=String.valueOf(x).length();

if (x<0)
length=length-2;
else
length=length-1;

while(x/10!=0) {
temp=(x%10)*(Math.pow(10, length));
sum=(int) (temp+result);
if(Math.abs(temp)>Math.abs(sum)-Math.abs(result))
return 0;
result+=temp;
x/=10;
length--;
}

sum=result+x;
if(Math.abs(x)>Math.abs(sum)-Math.abs(result))
return 0;
result+=x;
return result;
}
}

 
posted @ 2018-02-25 22:04  同销万古愁  阅读(107)  评论(0编辑  收藏  举报