forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.java
More file actions
43 lines (41 loc) · 1.39 KB
/
Copy pathDivideTwoIntegers.java
File metadata and controls
43 lines (41 loc) · 1.39 KB
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
43
/*
Divide two integers without using multiplication, division and mod operator.
*/
// map + bit manipulation
public class Solution {
public int divide(int dividend, int divisor) {
if (dividend == 0 || divisor == 0) return 0;
long d = Math.abs((long)dividend); // avoid overflow, abs(Integer.MIN_VALUE) = Integer.MIN_VALUE
long s = Math.abs((long)divisor);
Map<Integer, Long> map = new HashMap<Integer, Long>(); // divisor mapping
int key = 0;
while (s <= d){
map.put(key++, s);
s = s << 1;
}
int res = 0;
while (--key >= 0 ){ // remember to '--' first
if (d >= map.get(key)){
d -= map.get(key);
res += 1 << key;
}
}
return (dividend > 0) ^ (divisor > 0) ? -res : res; // ^ is both bitwise and logical XOR in java
}
}
// See Company/amazon/BitDivision
// time: O(32); space: O(1)
public class Solution {
public int divide(int dividend, int divisor) {
if (dividend==0) return 0;
long a = Math.abs((long)dividend), b = Math.abs((long)divisor);
int res = 0, i=31;
while (i>=0 && a>0){
if ((a>>i)>=b){
a -= (b<<i);
res += (1<<i);
}else i--;
}
return (dividend^divisor)>=0? res: -res;
}
}