leetcode Divide Two Integers

265 篇文章 1 订阅
231 篇文章 0 订阅

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

There are two major problems:

1. The minimal int is also a test case, so long long is essential. 

2. return (1<<(k - 1)) + div(dividend - (divisortmp>>1), divisor); is wrong because of the priority. 

The right code is :

class Solution {
 public:
  long long abs(long long x) {
    return x > 0 ? x : (-x);
  }
  int div (long long dividend, long long divisor) {
    if (dividend < divisor)
      return 0;
    int k = 0;
    long long divisortmp = divisor;
	for (; dividend >= divisortmp; ++k)
      divisortmp <<= 1;
    return (1<<(k - 1)) + div(dividend - (divisortmp>>1), divisor);
  }
  int divide(int dividend, int divisor) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if (divisor == 0 || dividend == 0)
      return 0;
    int sign[3]; // - is 1; + is 0
    sign[0] = dividend < 0 ? 1 : 0;
    sign[1] = divisor < 0 ? 1 : 0;
    sign[2] = sign[0]^sign[1];
    
	long long divisorll = abs((long long)divisor);
	long long dividendll = abs((long long)dividend);
    int res = div(dividendll, divisorll);
    return sign[2] == 0 ? res : -res;
  }
};

 A better solution:

class Solution {
 public:
  inline long long abs(long long x) {
    //x may be the INT_MIN
    return x > 0 ? x : -x; 
  }
  int divide(int dividend, int divisor) {
    long long a = abs(dividend), b = abs(divisor);
    //int res = 0; // So int is not enough
    long long res = 0;
    while (a >= b) {
      long long c = b;
      for (int i = 0; a >= c; ++i, c <<= 1) {
        res += 1 << i;
        a -= c;
      }
    }
    res = (dividend ^ divisor) >> 31 ? -res : res;
    return (int)res;
  }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值