首页 > 其他 > 详细

leetcode——Divide Two Integers

时间:2015-03-13 08:08:38      阅读:233      评论:0      收藏:0      [点我收藏+]

题目:

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

If it is overflow, return MAX_INT.

题意:

不用乘号、除号、取模运算来模拟除法。

分析:

一开始每回减去一次除数,这样会超时,优化是减去除数*2^n,用左移运算可以实现每次翻2倍.

class Solution {
public:
    // 每次被除数翻倍,来增加效率
    int divide(int dividend, int divisor) {
        // c左移n位就是c*2^n
        // 先转为正数再运算,因为INI_MIN转为正数会溢出,所以用先转为longlong类型再转为负数
        long long a = dividend>=0 ? dividend : -(long long)dividend;
        long long b = divisor>=0 ? divisor : -(long long)divisor;
        // 被除数每次翻倍,若超过除数了再从1倍开始翻倍
        // i是倍数
        long long ret  = 0;
        while(a>=b){
            long long c = b;
            for(int i = 0; a >= c; i ++, c <<= 1){
                a -= c;
                ret += (1<<i);
            }
        }
        // 当被除数是-2147483648时,异或可能会溢出,所以异或也要用longlong类型
        // 异或除数和被除数,若都是同号则为假,异号则为真
        // 因为最左边第64位是符号位,所以要右移63位
        ret = (((long long)(dividend^divisor))>>63) ? -ret : ret;
        if(ret>INT_MAX) return INT_MAX;
        return ret;
    }
};

leetcode——Divide Two Integers

原文:http://www.cnblogs.com/skysand/p/4334215.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!