码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Divide Two Integers

时间:2015-03-19 08:50:24      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

There couple of edge cases need to remember:

1. The result, absolute value of dividend and divisor. Otherwise, when the record goes out of boundary, the result will be invalid.

2. use long long int as the current value to compare with divd. Because condition is (current << i) <= divd. When the loop break, current may already exceed INT_MAX

 1 class Solution {
 2 public:
 3     int divide(int dividend, int divisor) {
 4         unsigned int divd = fabs(dividend), divs = fabs(divisor), result = 0;
 5         long long int current = 0;
 6         int i = 0;
 7         while (divd >= divs) {
 8             current = divs;
 9             for (i = 0; (current << i) <= divd; i++);
10             result += (1 << (i-1));
11             divd -= (divs << (i-1));
12             if (result > INT_MAX) return (dividend < 0 ^ divisor < 0) ? INT_MIN : INT_MAX;
13         }
14         return (dividend < 0 ^ divisor < 0) ? -result : result;
15     }
16 };

 

LeetCode – Refresh – Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4349380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!