标签:
1 class Solution 2 { 3 public: 4 int divide(int dividend, int dividor) 5 { 6 if(dividend == INT_MIN && dividor == -1) 7 return INT_MAX; 8 9 auto sign = [=] (int x) -> int { return x>0? 1 : -1;}; 10 int p1 = sign(dividend); 11 int p2 = sign(dividor); 12 13 long long n1 = abs(static_cast<long long>(dividend)); 14 long long n2 = abs(static_cast<long long>(dividor)); 15 16 long long ret = 0; 17 long long pre_ret = 0; 18 while(n1 >= n2) 19 { 20 if(ret == 0 && pre_ret == 0) 21 { 22 pre_ret = 1; 23 ret = 1; 24 } 25 else 26 { 27 pre_ret += pre_ret; 28 ret = pre_ret + ret; 29 } 30 31 n1 -= n2; 32 n2 += n2; 33 } 34 35 while(n2 >= abs(static_cast<long long>(dividor)) && n1 >= abs(static_cast<long long>(dividor))) 36 { 37 if(pre_ret == 0) 38 { 39 ret += 1; 40 break; 41 } 42 43 if(n1 < n2) 44 { 45 n2 = n2 >> 1; 46 if(n1 == n2) 47 { 48 ret += pre_ret; 49 break; 50 } 51 pre_ret = pre_ret >> 1; 52 } 53 else 54 { 55 n1 -= n2; 56 n2 = n2 >> 1; 57 if(n1 == n2) 58 { 59 ret += pre_ret; 60 break; 61 } 62 ret = pre_ret + pre_ret + ret; 63 pre_ret = pre_ret >> 1; 64 } 65 } 66 67 if(p1 == p2) 68 return ret; 69 else 70 return -ret; 71 } 72 };
[leetcode] Divide Two Integers
标签:
原文地址:http://www.cnblogs.com/lxd2502/p/4386448.html