Leetcode 29. Divide Two Integers

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

《Leetcode 29. Divide Two Integers》 Divide Two Integers

2. Solution

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(dividend == INT_MIN && divisor == -1) {
            return INT_MAX;
        }
        int sign = (dividend > 0) ^ (divisor > 0)?-1:1;
        long x = labs(dividend);
        long y = labs(divisor);
        int result = 0;
        int power= 1;
        while(x >= y) {
            long temp = y;
            power = 1;
            while(x >= (temp << 1)) {
                temp <<= 1;
                power <<= 1;
            }
            x -= temp;
            result += power;
        }
        return sign>0?result:-result;
    }
};

Reference

  1. https://leetcode.com/problems/divide-two-integers/description/
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/e994fea1638d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞