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

62. Divide Two Integers

时间:2014-09-09 10:37:28      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   div   问题   sp   log   

Divide Two Integers

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

思路: 类同 趣味算法之数学问题:题4. 

两点需要注意: 1. 除数或被除数为最大负数时,转化为正数会溢出。2. divisor + divisor 可能会溢出。

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(divisor == 0) return INT_MAX;
        bool signal = false;
        bool overflow = false;
        if(dividend < 0) {
            signal = !signal;
            if(dividend == INT_MIN) { overflow = true; dividend++; }
            dividend *= -1;
        } 
        if(divisor < 0) {
            signal = !signal;
            if(divisor == INT_MIN) {
                if(overflow) return 1;
                else return 0;
            }
            divisor *= -1;
        }
        int result = 0;
        while(dividend >= divisor) {
            int x(divisor);
            int r(1);
            while(dividend-x >= x) {
                x += x;
                r += r;
            }
            dividend -= x;
            result += r;
        }
        if(overflow && dividend +1 == divisor) result++;
        return signal ? (-result) : result;
    }
};

 

62. Divide Two Integers

标签:style   blog   http   io   ar   div   问题   sp   log   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3961196.html

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