[LeetCode 解题报告]029. Divide Two Integers

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/caicaiatnbu/article/details/102762674

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

考察:int类型两数整除结果,转化为高阶long long类型来运算,如果溢出则返回INT_MAX, 尽可能去使用位移动,以及异或运算求符号;

class Solution {
public:
    int divide(int dividend, int divisor) {
        long long res = 0;
        long long m = abs((long long)dividend), n = abs((long long)divisor);
        if (m < n)
            return 0;
        long long t = n, p = 1;
        while (m > (t << 1)) {
            t <<= 1;
            p <<= 1;
        }
        res += p + divide(m-t, n);
        
        if ((dividend < 0) ^ (divisor < 0)) //符号取异或
            res = -res;
        return res > INT_MAX ? INT_MAX : res; // 判断是否溢出
       
    }
};

 完,

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/102762674