LeetCode29. 两数相除
题目
分析
代码
1 class Solution 2 { 3 public: 4 int divide(int x, int y) 5 { 6 typedef long long ll; 7 vector<ll> exp; 8 bool is_minus = false; 9 10 if ((x > 0 && y < 0 )|| (x < 0 && y > 0)) 11 is_minus = true; 12 13 ll a = abs((ll)x), b = abs((ll)y); 14 for (ll i = b; i <= a; i = i + i) 15 exp.push_back(i); 16 17 ll res = 0; 18 for (int i = exp.size() - 1; i >= 0; i--) 19 { 20 if ( a >= exp[i]) 21 { 22 a -= exp[i]; 23 res += 1ll << i; //2的i次方 ,注意31次方移位会溢出所以转ll 24 25 } 26 } 27 28 if (is_minus) 29 res = -res; 30 31 if (res > INT_MAX || res < INT_MIN) 32 res = INT_MAX; 33 return res; 34 } 35 };