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

Divide Two Integers

时间:2015-10-12 01:47:42      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return MAX_INT.

 

Runtime: 8ms

 1 class Solution {
 2 public:
 3     int divide(int dividend, int divisor) {
 4     if(divisor == 0) return INT_MAX;
 5     
 6     long long newDividend = dividend;
 7     if(newDividend < 0) newDividend = -newDividend;
 8     long long newDivisor = divisor;
 9     if(newDivisor < 0) newDivisor = -newDivisor;
10     
11     bool negative = ((dividend < 0 && divisor > 0 )|| (dividend > 0 && divisor < 0));
12     long long divis = newDivisor;
13 
14     long long result = 0;
15     while(divis <= newDividend){
16         long long times = 1;
17         
18         while(divis <= newDividend){
19             divis <<= 1;
20             times <<= 1;
21         }
22         newDividend -= (divis >> 1);
23         divis = newDivisor;
24         result += (times >> 1);
25     }
26     if(result > INT_MAX){
27         if(negative && result + INT_MIN <= 0)
28             result = result;
29         else
30             result = INT_MAX;
31     }
32     return negative ? -result : result;
33 }
34 };

 

Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4870547.html

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