LeetCode: Divide Two Integers
2012-11-29 12:20
344 查看
Divide two integers without using multiplication, division and mod operator.
睡眠不够,脑子明显不好使了,明天得补补觉了。
今天写的
睡眠不够,脑子明显不好使了,明天得补补觉了。
class Solution { public: int divide(int dividend, int divisor) { // Start typing your C/C++ solution below // DO NOT write int main() function int count = 0; int offset = 0; long long num = abs((long long)dividend); long long n_divisor = abs((long long)divisor); while(num >= n_divisor){ n_divisor <<= 1; offset++; } while(offset >= 0){ while(num >= n_divisor) { count += 1 << offset; num -= n_divisor; } n_divisor>>=1; offset--; } if(!isSame(dividend, divisor)) { count = 0 - count; } return count; } bool isSame(int a, int b){ if(a >= 0 && b >= 0){return true;} if(a < 0 && b < 0){return true;} return false; } };
今天写的
class Solution { public: int divide(int dividend, int divisor) { // Start typing your C/C++ solution below // DO NOT write int main() function int offset = 0; long long temp = abs((long long)divisor); bool is_neg = false; if((dividend>> 31 & 1) ^ (divisor>>31 & 1)) is_neg = true; long long dvd = abs((long long)dividend); while(temp <= dvd){ temp<<=1; ++offset; } int count = 0; while(offset > -1){ while(dvd >= temp){ dvd -= temp; count += 1<<offset; } temp>>=1; offset--; } if(is_neg) return 0 - count; return count; } };
相关文章推荐
- leetcode Divide Two Integers
- **LeetCode-Divide Two Integers
- 51_leetcode_Divide Two Integers
- LeetCode 28. Divide Two Integers
- Leetcode Divide Two Integers
- Leetcode: Divide Two Integers
- LeetCode 29. Divide Two Integers
- leetcode 29:Divide Two Integers
- [LeetCode] Add Two Numbers、Divide Two Integers、Multiply Strings、Add Binary、Plus One
- leetcode29 Divide Two Integers
- leetcode 29. Divide Two Integers
- [leetcode]Divide Two Integers
- [Leetcode] Divide Two Integers (Java)
- [leetcode刷题系列]Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode 29 - Divide Two Integers
- LeetCode 29 Divide Two Integers 除法的原理
- leetcode:Divide Two Integers
- Leetcode: Divide Two Integers
- [LeetCode] Divide Two Integers