-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem 29.java
More file actions
42 lines (29 loc) · 789 Bytes
/
Problem 29.java
File metadata and controls
42 lines (29 loc) · 789 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public int divide(int dividend, int divisor) {
if(dividend==divisor){
return 1;
}
boolean sign = true; // positive
if(dividend >=0 && divisor <0){
sign =false;
}
if(dividend <0 && divisor >0){
sign =false;
}
long n = Math.abs((long) dividend);
long d = Math.abs((long) divisor);
long ans=0;
while(n>=d){
int c=0;
while(n>=(d<<(c+1))){
c++;
}
ans=ans+(1L<<c);
n=n-(d<<c);
}
if (ans > Integer.MAX_VALUE) {
return sign ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
return sign? (int) ans : (int) -ans;
}
}