美文网首页计算机
Leetcode - Divide Two Integers

Leetcode - Divide Two Integers

作者: Richardo92 | 来源:发表于2016-09-23 03:42 被阅读3次

My code:

public class Solution {
    public int divide(int dividend, int divisor) {
        if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) {
            return Integer.MAX_VALUE;
        }
        int sign = (dividend < 0 == divisor < 0 || dividend == 0) ? 1 : -1;
        long num = Math.abs((long) dividend);
        long div = Math.abs((long) divisor);
        int sum = 0;
        while (num >= div) {
            long temp = div;
            long counter = 1;
            while (num >= (temp << 1)) {
                temp <<= 1;
                counter <<= 1;
            }
            num -= temp;
            sum += counter;
        }
        
        return sign * sum;
    }
}

reference:
https://discuss.leetcode.com/topic/15568/detailed-explained-8ms-c-solution

这道题目没能自己做出来。觉得太麻烦了。
其实和 Fraction to Recurring Decimal 差不多。
只不过那道题目关注的是小数点循环。
这道题目关注的是,如何更快地算出结果。
那自然是 Binary search, 但是是双层循环。这是我没能想到的。

Anyway, Good luck, Richardo! -- 09/22/2016

相关文章

网友评论

    本文标题:Leetcode - Divide Two Integers

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