29. Divide Two Integers(C++)

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

If it is overflow, return MAX_INT.

 

 

solution:

 1 class Solution {
 2 public:
 3     int divide(int dividend, int divisor) {
 4         int count=0;
 5         if (!divisor || (dividend == INT_MIN && divisor == -1))
 6             return INT_MAX;
 7         int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
 8         long long dvd = labs(dividend);
 9         long long dvs = labs(divisor);
10         while(dvd>=dvs){
11             long long tmp=dvs,mult=1;
12             while(dvd>=(tmp<<1)){
13                 tmp=tmp<<1;
14                 mult=mult<<1;
15             }
16             dvd-=tmp;
17             count+=mult;
18         }
19         return sign==1?count:-count;
20     }
21 };

 

posted @ 2017-03-08 16:22  DevinGu  阅读(249)  评论(0编辑  收藏  举报