TypechoJoeTheme

IT技术分享

统计

[LeetCode 29] Divide Two Integers [Java]

2017-12-22
/
0 评论
/
773 阅读
/
正在检测是否收录...
12/22

1. Description

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

2. Code

public class LeetCode0029 {
    public int divide(int dividend, int divisor) {
        if (divisor == 0) {
            return Integer.MAX_VALUE;
        }
        if (divisor == -1 && dividend == Integer.MIN_VALUE) {
            return Integer.MAX_VALUE;
        }

        long pDividend = Math.abs((long) dividend);
        long pDivisor = Math.abs((long) divisor);

        int result = 0;

        while (pDividend >= pDivisor) {
            int shift = 1;
            while (pDividend >= (pDivisor << shift)) {
                shift++;
            }
            shift--;
            result += 1 << shift;
            pDividend -= pDivisor << shift;
        }

        if (dividend > 0 && divisor > 0 || dividend < 0 && divisor < 0) {
            return result;
        } else {
            return -result;
        }
    }

    public static void main(String[] args) {
        LeetCode0029 leetcode = new LeetCode0029();
        System.out.println(leetcode.divide(9, 2));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1298/(转载时请注明本文出处及文章链接)