[leetcode]29. Divide Two Integers

来源:互联网 发布:网络教育专业推荐 编辑:程序博客网 时间:2024/06/04 19:05

题目链接:https://leetcode.com/problems/divide-two-integers/description/


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

If it is overflow, return MAX_INT.


class Solution {public:    int divide(int dividend, int divisor) {        if(!divisor || (dividend==INT32_MIN && divisor==-1))            return INT32_MAX;        int sign=(dividend<0 ^ divisor<0)?-1:1;        long long dvd=labs(dividend);        long long dvs=labs(divisor);        int res=0;        while(dvd>=dvs)        {            long long temp=dvs,multiple=1;            while(dvd>=(temp<<1))            {                temp<<=1;                multiple<<=1;            }            dvd-=temp;            res+=multiple;        }        return sign==1?res:-res;    }};


原创粉丝点击