leetcode: Divide Two Integers

http://oj.leetcode.com/problems/divide-two-integers/

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

思路

典型的二分法。以87除4举例, (4 * 2 = 8) => (8 * 2 = 16) => (16 * 2 = 32) => (32 * 2) => 64,因为64 * 2 = 128大于87,现在我们可以确定4 * 16 = 64小于87,那么再处理87 - 64 = 23,23除4的话用上面方法可以得到5,还余3,因为小于4,扔掉,所以最后结果是16 + 5 = 21。因为需要考虑溢出问题,所以先把数字转换为unsigned long long,最后转成int返回。

 1 class Solution {
 2 public:
 3     long long internalDivide(unsigned long long dividend, unsigned long long divisor) {
 4         if (dividend < divisor) {
 5             return 0;
 6         }
 7         
 8         long long result = 1;
 9         unsigned long long tmp = divisor, left;
10         
11         while (tmp <= dividend) {
12             left = dividend - tmp;
13             tmp <<= 1;
14             
15             if (tmp > dividend) {
16                 break;
17             }
18             else {
19                 result <<= 1;
20             }
21         }
22         
23         return result + internalDivide(left, divisor);
24     }
25     
26     int divide(int dividend, int divisor) {
27         unsigned long long _dividend = abs((long long)dividend), 
28             _divisor = abs((long long)divisor);
29         bool positive = ((dividend >= 0) && (divisor > 0)) || ((dividend <= 0) && (divisor < 0));
30         
31         return positive ? internalDivide(_dividend, _divisor) : (-1) * internalDivide(_dividend, _divisor);
32     }
33 };

 

 

posted @ 2013-10-30 16:18  移山测试工作室黑灯老师  阅读(2317)  评论(1编辑  收藏  举报
count website visits
Buy Computers