leecode(29) Divide Two Integers

来源:互联网 发布:mathcad读取数据 编辑:程序博客网 时间:2024/05/22 01:53

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


题目:29. Divide Two Integers

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

If it is overflow, return MAX_INT.

解题思路:

(1)两数相除,因为不能用算数运算的乘除来做,所以首先想到的就是用不停的用减法来做。

(2)考虑都为正整数的情况,m = a/b   => a = m*b + 余数  =》 a-b-b-b....(减去m个b) = 余数

(3)但是按照(2)的思路进行编码会超时,因为有可能,b相对a来说比较小,这样循环减的次数过多。

所以,这里我们使用了位运算,来扩大步长,防止超时现象。

(4)即,若a-b>0 ,则下一次,让b扩大成2倍,a=a-b,若仍然a-2*b>0,接着a=a-2*b,b继续扩展2倍,即变为4*b,继续比较a-4*b,,,,,逐次递归。


代码如下:

#include <stdio.h>
#include <limits.h>
#include <math.h>

int divide(int dividend, int divisor) {
    int count = 0;
    int flag = 1;
    unsigned int abs_dividend = dividend > 0?dividend:-dividend;
    unsigned int abs_divisor = divisor > 0?divisor:-divisor;
    unsigned int temp;
    unsigned int result = 0;
    if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
        flag = -1;
    }
    if (divisor == 0) {
        return INT_MAX;
    }
    while (abs_dividend >= abs_divisor) {
        count = 1;
        temp = abs_divisor;
        while (abs_dividend >= temp) {
            //printf("==abs_dividend:%d===temp:%d===\n", abs_dividend, temp);
            abs_dividend = abs_dividend - temp;
            result = result + count;
            if (temp < (INT_MAX >> 1)){ //防止temp*2之后溢出
                temp = temp << 1;
                count = count << 1;
            }
        }
        //printf("---abs_dividend:%d----abs_divisor:%d", abs_dividend, abs_divisor);
    }
    if (result > INT_MAX && flag == 1) {
        return INT_MAX;
    }
    return result * flag;
}

int main() {
    int a = 41, b = 4;
    int result = divide(a, b);
    printf("%d", result);
}

注意一下边界情况!所以在求绝对值得时候,使用的是unsigned int,防止之前是负数,转成正数之后溢出了。

0 0