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

Leetcode-Divide Two Integers

时间:2014-12-16 07:40:01      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   on   div   log   bs   

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

标签:style   blog   io   color   sp   on   div   log   bs   

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

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