美文网首页LeetCode
[LeetCode] 7. Reverse Integer

[LeetCode] 7. Reverse Integer

作者: xxx亦凡桑 | 来源:发表于2017-05-04 20:02 被阅读0次

    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>

    相关文章

      网友评论

        本文标题:[LeetCode] 7. Reverse Integer

        本文链接:https://www.haomeiwen.com/subject/lcydtxtx.html