码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Divide Two Integers

时间:2015-02-22 17:23:05      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return MAX_INT.

题意:不用乘除和mod运算计算两个数相除。

思路:因为每个数都能表示为二进制,也就是num = a*2^0 + b*2^1....,所以我们只要去判断有哪些2^k就能相加得到结果了,第一种方式是循环,第二种写法是每次找到最大2^k,这道题就是把2换成b就是了

class Solution {
public:
    int divide(int dividend, int divisor) {
        
        long long a = abs((double)dividend);       
        long long b = abs((double)divisor);
        long long res = 0;
        while (a >= b) {
            long long c = b;
            for (int i = 0; a >= c; i++, c <<= 1) {
                a -= c;
                res += 1<<i;
            }
        }

        int flag = ((divisor ^ dividend) >> 31) ? -1 : 1;
        if (res * flag > INT_MAX)
            return INT_MAX;
        else return res * flag;
    }
};


class Solution {
public:
    int divide(int dividend, int divisor) {
        long long a = abs((double)dividend);       
        long long b = abs((double)divisor);
        long long res = 0;
        while(a >= b) {
             long long t = b, i = 1;
             while((t << 1) < a) {
                 t <<= 1;
                 i <<= 1;
             }
             a -= t;
             res += i;
        }

        int flag = ((divisor ^ dividend) >> 31) ? -1 : 1;
        if (res * flag > INT_MAX)
            return INT_MAX;
        else return res * flag;
    }
};



LeetCode Divide Two Integers

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/43907761

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!