首页 > 代码库 > Divide Two Integers leetcode java
Divide Two Integers leetcode java
题目:
Divide two integers without using multiplication, division and mod operator.
题解:
这道题我自己没想出来。。。乘除取模都不让用。。那只有加减了。。。我参考的http://blog.csdn.net/perfect8886/article/details/23040143
代码如下:
1 public int divide(int dividend, int divisor) {
2 if (dividend == 0 || divisor == 0) {
3 return 0;
4 }
5 boolean isNeg = (dividend > 0 && divisor < 0)
6 || (dividend < 0 && divisor > 0);
7 long a = Math.abs((long) dividend);
8 long b = Math.abs((long) divisor);
9 if (b > a) {
10 return 0;
11 }
12
13 long sum = 0;
14 long pow = 0;
15 int result = 0;
16 while (a >= b) {
17 pow = 1;
18 sum = b;
19 while (sum + sum <= a) {
20 sum += sum;
21 pow += pow;
22 }
23 a -= sum;
24 result += pow;
25 }
26 return isNeg ? -result : result;
27 }
2 if (dividend == 0 || divisor == 0) {
3 return 0;
4 }
5 boolean isNeg = (dividend > 0 && divisor < 0)
6 || (dividend < 0 && divisor > 0);
7 long a = Math.abs((long) dividend);
8 long b = Math.abs((long) divisor);
9 if (b > a) {
10 return 0;
11 }
12
13 long sum = 0;
14 long pow = 0;
15 int result = 0;
16 while (a >= b) {
17 pow = 1;
18 sum = b;
19 while (sum + sum <= a) {
20 sum += sum;
21 pow += pow;
22 }
23 a -= sum;
24 result += pow;
25 }
26 return isNeg ? -result : result;
27 }
Reference:
http://blog.csdn.net/perfect8886/article/details/23040143
Divide Two Integers leetcode java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。