[leetcode Q29] Divide Two Integers

来源:互联网 发布:仙界网络直播间书包网 编辑:程序博客网 时间:2024/05/22 01:52

1. 题目

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

If it is overflow, return MAX_INT.

要求不使用乘除法实现两个整数相除运算。

2. 思路

不使用乘法除法,要想快数得到结果就只能考虑位运算。本题主要考察位运算。

  • 被除数减去一次除数,结果 + 1
  • 被除数减去 2 x 除数,结果 + 2
  • 被除数减去 4 x 除数,结果 + 4
  • ……

需要注意整数溢出

如输入:

-21474836481-2147483648-1

3. 实现

class Solution {public:    int divide(int dividend, int divisor) {           // Note: The Solution object is instantiated only once.              if (divisor == 1)                return dividend;            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;                  }              }            if (res == 0x80000000)                return 2147483647;            else                return ((dividend ^ divisor) >> 31) ? (-res) : (res);          }  };
0 0
原创粉丝点击