leetcode :Binary Search: Divide Two Integers(029)

原创 2016年08月28日 15:56:43

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

If it is overflow, return MAX_INT.


算法

o(nlgn)



typedef long long ll;
class Solution {
public:
    int divide(int dividend, int divisor) {
        ll a = dividend >= 0 ? dividend : -(ll)dividend;
        ll b = divisor >= 0 ? divisor : -(ll)divisor;
        ll result = 0, c = 0;
        bool sign = (dividend > 0 && divisor < 0) ||
            (dividend < 0 && divisor > 0);

        while (a >= b) {
            c = b;
            for (int i = 0; a >= c; i++, c <<= 1) {
                a -= c;
                result += (1<<i);
            }
        }
        if (sign) {
            return max((ll)INT_MIN, -result);
        } else {
            return min((ll)INT_MAX, result);
        }
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

[LeetCode]029-Divide Two Integers

题目: Divide two integers without using multiplication, division and mod operator.If it is overflow, ...

LeetCode 029 Divide Two Integers

题目要求返回两个int的整除结果,但是不能使用乘号、除号、取模运算符。

LeetCode 029. Divide Two Integers

Divide Two Integers Divide two integers without using multiplication, division and mod oper...

LeetCode029 Divide Two Integers

详细见:leetcode.com/problems/divide-two-integers Java Solution: github package leetcode; publi...
  • zxwtry
  • zxwtry
  • 2017年04月02日 13:11
  • 79

【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers(两个整数相除)】

【029-Divide Two Integers(两个整数相除)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Divide two integers without u...

leetcode 029 Divide Two Integers

Divide two integers without using multiplication, division and mod operator. If it is overflow, re...

29. Divide Two Integers/49. Group Anagrams/96. Unique Binary Search Trees/560. Subarray Sum Equals K

Divide Two Integers Problem Description Implementation29. Divide Two IntegersProblem DescriptionDivi...

Binary search (4) -- Find Right Interval,Count Complete Tree Nodes,Divide Two Integers

Find Right Interval,Count Complete Tree Nodes,Divide Two Integers
  • dwt0317
  • dwt0317
  • 2017年01月18日 15:12
  • 109

LeetCode 29. Divide Two Integers 二进制分解

题目Divide two integers without using multiplication, division and mod operator.If it is overflow, ret...

LeetCode29 - divide two Integers

LeetCode29 - Divide Two Integer
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode :Binary Search: Divide Two Integers(029)
举报原因:
原因补充:

(最多只允许输入30个字)