LeetCode

[LeetCode] 7. Reverse Integer

2017-05-04  本文已影响0人  xxx亦凡桑

Reverse digits of an integer.

Example1:
x = 123, return 321
Example2:
x = -123, return -321

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


</br>

Solution

This solution is pretty straightforward, we only have to get the last digit of the number and output it. To achieve which, it is obvious to use division; by applying x % 10, and the remainder is the value of that digit.

Other than this, we also have to take care the overflow problem. How can we identify whether there is a overflow? Because the input is a 32-bit signed integer, we can then use a 64-bit long to store the output and compare to the int version of the same output. If two values are not the same, then we can conclude that there should be a overflow.

The code is shown as below.

Java

public class Solution {
    public int reverse(int x) {
        
        int pos = Math.abs(x);
        int divide = pos, len = 0;
        long output = 0;
        
        while (divide > 0){
            divide = divide / 10;
            len ++;
        } 
        
        for (int i = 0; i < len; i++){
            output += (pos % 10) * Math.pow(10,len-i-1);
            pos = pos / 10;
        }
        
        int overflow = (int) output;
        if ( overflow != output )
            return 0;
            
        if(x<0)
            output = -output;
            
        return (int)output;
    }
}

</br>

上一篇下一篇

猜你喜欢

热点阅读