Sunday, June 9, 2013

Divide 2 integers@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Divide two integers without using multiplication, division and mod operator.
» Solve this problem

In the first beginning, I use minus operator to minus the divisor each time, until the dividend is smaller than the divisor. Though this method can work out, yet it is toooo slow. Especially in the case that the dividend is too large while the divisor is too small.

So we can use the bit operation here.

See the algorithm below. It move the divisor one step left each time, so the divisor*2 each time. Then dividend-divisor, and count+=1<<i. When dividend minus i times of divisor, then, count will add i correspondingly.

In the mean time, we need to pay attention to the positive/negative sign of dividend and divisor.
We use(dividend^divisor)>>31. Why move 31 steps right? Because the highest bit represent the sign of an integer.

There are two solutions given below. The second one can pass the tests. Because we can see that it let's the divisor grows in exponential order.

There are some places we need to pay attention is,
1. Use long long instead of int. Because INT_MIN = -INT_MAX-1, thus when we transfer the dividend or divisor to abs value, if one of them is INT_MIN, after transferring, it will overflow.

2. We need to define as long long a = dividend, then a = abs(a). We can't do long long a = abs(dividend). Otherwise the type won't be changed.

3. XOR bit manipulation. The rule is F^F = F, T^T = F, T^F = T. Means when two things are the same, it will be F, otherwise it will be T.


4 comments:

  1. lz牛掰,这个代码写的很简洁啊

    ReplyDelete
  2. Replies
    1. 其实就是因为一个整数可以表示成以2的幂为底的一组基的线性组合,比如:num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n。
      bit manipulation相当于每次除以2,递减速度快,为log(n),比用线性的减法快。

      Delete
  3. 楼主能不能讲细点啊,只是在复述代码啊PS,和另一篇博文的代码一模一样

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...