首页 > 其他 > 详细

Leetcode-Divide Two Integers

时间:2014-12-16 07:37:18      阅读:221      评论:0      收藏:0      [点我收藏+]

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

If it is overflow, return MAX_INT.

Solution:

 1 public class Solution {
 2     public int divide(int dividend, int divisor) {
 3         if (divisor==0) return Integer.MAX_VALUE;
 4         if (dividend==0) return 0;
 5         if (divisor==1) return dividend;
 6         if (dividend==Integer.MIN_VALUE && divisor==-1) return Integer.MAX_VALUE;
 7 
 8         boolean neg = false;
 9         //change to all negtive number.
10         if (dividend>0){
11             dividend = -dividend;
12             neg = !neg;
13         }
14         if (divisor>0){
15             divisor = - divisor;
16             neg = !neg;
17         }
18 
19         int minDivisor = Integer.MIN_VALUE >> 1;
20         int cur = divisor;
21         int val = 1;
22         while (cur>=minDivisor && cur>dividend){
23             cur <<= 1;
24             val <<= 1;
25         }
26 
27         int res = 0;
28         while (dividend<=divisor){
29             while (cur<dividend){
30                 cur >>= 1;
31                 val >>= 1;
32             }
33             dividend -= cur;
34             res += val;
35         }
36 
37         if (neg) return -res;
38         else return res;
39     }
40 }

 

Leetcode-Divide Two Integers

原文:http://www.cnblogs.com/lishiblog/p/4166263.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!