Saturday, March 19, 2016

LeetCode 刷题第一阶段 Inverse Integer

之前混乱地刷了一些 LeetCode 的题目, 经大神提点,现今决定进入系统刷题。第一阶段是 自主快速刷完所有easy难度的题。之后的阶段求最优解加上进阶medium, hard。


2016. 3. 19
inverse integer:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

consideration:
思路比较简单直接,但是博主考虑到restore x 的问题, 然而网上大家都没有考虑相应问题, 题目也没有要求restore 故此处不管。 具体面试的时候可以问考官。
***** 但是要考虑overflow 问题。
The input can be in int range but the output might overflow , for example, if you input (INT_MAX-1), the output will be out of range.
Till now, two solutions for it.
1. Change return answer to long type
2. set upper bound and lower bound to detect 


talk is cheap, show the code :
public class Solution {
    public int reverse(int x) {
        int res = 0;
        while(x != 0){
            int lastD = x % 10 ;
            int upBound = (Integer.MAX_VALUE - lastD) / 10 ;
            int loBound = (Integer.MIN_VALUE - lastD) / 10 ;
            
            if (x>0 && res > upBound) return 0;
            if (x<0 && res < loBound) return 0;

            x = x / 10 ;
            res = res * 10 + lastD ; 
        }
      
        return res;
    }
}

btw 这题也可以用recursion 做 就不写了这次。 因为overflow问题 耽误时间较长希望下次改进。

No comments:

Post a Comment