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

LeetCode Divide Two Integers

时间:2015-01-12 00:18:28      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return MAX_INT.

 

 1 public class Solution {
 2     public int divide(int dividend, int divisor) {
 3         if (dividend == 0) {
 4             return 0;
 5         }
 6 
 7         long a=dividend,b=divisor;
 8         boolean isNeg=false;
 9         if (dividend < 0) {
10             isNeg=!isNeg;
11             a=-a;
12         }
13         if (divisor < 0) {
14             isNeg = !isNeg;
15             b = -b;
16         }
17         long i=0;
18         if(b==1) {
19            i=a; 
20         }else
21         {
22             while (a >= b) {
23                 long temp = b;
24                 int k=1;
25                 while (temp + temp <= a) {
26                     k = k << 1;
27                     temp = temp + temp;
28                 }
29                 i = i | k;
30                 a = a - temp;
31             }            
32         }
33 
34         if (isNeg) {
35             i = -i;
36         }
37         if (i > Integer.MAX_VALUE || i < Integer.MIN_VALUE) {
38             return Integer.MAX_VALUE;
39         }        
40         return (int)i;
41     }
42 }

 

LeetCode Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4217299.html

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