-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathChapter20(Bitwise).js
More file actions
94 lines (72 loc) · 1.65 KB
/
Copy pathChapter20(Bitwise).js
File metadata and controls
94 lines (72 loc) · 1.65 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
function BitwiseAdd(a, b) {
while (b != 0) {
var carry = (a & b);
a = a ^ b;
b = carry << 1;
}
return a;
}
console.log(BitwiseAdd(4, 5)); // 9
function BitwiseNegate(a) {
return BitwiseAdd(~a, 1);
}
console.log(BitwiseNegate(9)); // -9
// negation with itself gives back original
console.log(BitwiseNegate(BitwiseNegate(9))); // 9
function BitwiseSubtract(a, b) {
return BitwiseAdd(a, BitwiseNegate(b));
}
console.log(BitwiseSubtract(5, 4)); // 1
function BitwiseMultiply(a, b) {
var m = 1,
c = 0;
if (a < 0) {
a = BitwiseNegate(a);
b = BitwiseNegate(b);
}
while (a >= m && b) {
if (a & m) {
c = BitwiseAdd(b, c);
}
b = b << 1;
m = m << 1;
}
return c;
}
console.log(BitwiseMultiply(4, 5)); // 20
function BitwiseDividePositive(a, b) {
var c = 0;
if (b != 0) {
while (a >= b) {
a = BitwiseSubtract(a, b);
c++;
}
}
return c;
}
console.log(BitwiseDividePositive(10, 2)); // 5
function BitwiseDivide(a, b) {
var c = 0,
isNegative = 0;
if (a < 0) {
a = BitwiseNegate(a); // convert to positive
isNegative = !isNegative;
}
if (b < 0) {
b = BitwiseNegate(b); // convert to positive
isNegative = !isNegative;
}
if (b != 0) {
while (a >= b) {
a = BitwiseSubtract(a, b);
c++;
}
}
if (isNegative) {
c = BitwiseNegate(c);
}
return c;
}
console.log(BitwiseDivide(10, 2)); // 5
console.log(BitwiseDivide(-10, 2)); // -5
console.log(BitwiseDivide(-200, 4)); // -50