美文网首页
29. Divide Two Integers

29. Divide Two Integers

作者: 尚无花名 | 来源:发表于2019-04-24 22:21 被阅读0次

    Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
    Return the quotient after dividing dividend by divisor.
    The integer division should truncate toward zero.
    Example 1:
    Input: dividend = 10, divisor = 3
    Output: 3
    Example 2:
    Input: dividend = 7, divisor = -3
    Output: -2
    Note:

    Both dividend and divisor will be 32-bit signed integers.
    The divisor will never be 0.
    Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

    这题应该用位运算做,但是这道题的边界条件很恶心,需要细细分析。
    首先我们先判断正负号,如果两个数符号相等则为正数,符号不同则为负数。
    然后算他们的绝对值, 用这两个绝对值进行运算。
    算的时候一定要注意转成long进行运算。
    先把除数左移,移到再移一位就比被除数大了就不移了。把移的位数记下来,加到ans里面。
    然后退出条件是被除数小于除数。

    class Solution {
        public int divide(int dividend, int divisor) {
            boolean negativeSign = ( (dividend < 0 && divisor > 0) ||
                            (dividend > 0 && divisor < 0));
            long dd = Math.abs((long) dividend);
            long ds = Math.abs((long) divisor);
            long cnt = 0;
            int bit = 0;
            while (dd >= ds) {
                bit = 0;
                while (dd >= (ds << (1 + bit))) bit++;
                cnt += (1L << bit);
                dd -= (ds << bit);
            }
            if (cnt > Integer.MAX_VALUE) {
                return negativeSign ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            if (!negativeSign) return (int) cnt;
            return  (int) (0L - cnt);
        }
    }
    

    相关文章

      网友评论

          本文标题:29. Divide Two Integers

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