首页 > 其他 > 详细

[leetcode] 29. divide two integers

时间:2016-12-27 14:06:25      阅读:156      评论:0      收藏:0      [点我收藏+]

这道题目一直不会做,因为要考虑的corner case 太多。

1. divisor equals 0.

2. dividend equals 0.

3. Is the result negative?

4. when dividend equals Integer.MIN_VALUE and divisor equals -1, the result will overflow. convert result to long and then to integer.

5. have to use divided by divisor * 2 ^ n to avoid exceeding time limit

6. have to convert divisor and dividend to long to avoid overflow in shift.

7. constant 1 in java is compiled as integer by default.

public class Solution {
    public int divide(int dividend, int divisor) {
        if (divisor == 0) {
            return dividend >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        if (dividend == 0) {
            return 0;
        }
        boolean isNegative = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
        long x = Math.abs((long)dividend);
        long y = Math.abs((long)divisor);
        long result = 0;
        while (x >= y) {
            int a = 0;
            while (x >= (y << a)) {
                a++;
            }
            a--;
            result += (long)1 << a;
            x -= y << a;
        }
        if (result == (long) Integer.MAX_VALUE + 1) {
            return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
        return isNegative ? -(int)result : (int)result;
    }
}

 

[leetcode] 29. divide two integers

原文:http://www.cnblogs.com/Gryffin/p/6225420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!