29 Divide Two Integers

1 题目

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.

2 标准解

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

 

你可能感兴趣的:(#,Attempted,#,Math,#,Medium,LeetCode,#,BinarySearch)