Skip to content

Commit 2fba5d0

Browse files
authored
Update 1009-complement-of-base-10-integer.js
1 parent 46ab5f3 commit 2fba5d0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

1009-complement-of-base-10-integer.js

+28
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,31 @@ const bitwiseComplement = function (N) {
1414
// flip all bits
1515
return bitmask ^ N
1616
}
17+
18+
// another
19+
20+
/**
21+
* @param {number} N
22+
* @return {number}
23+
*/
24+
const bitwiseComplement = function (N) {
25+
let X = 1;
26+
while (N > X) X = X * 2 + 1;
27+
return N ^ X;
28+
}
29+
30+
// another
31+
32+
/**
33+
* @param {number} N
34+
* @return {number}
35+
*/
36+
const bitwiseComplement = function (N) {
37+
if (N === 0) return 1
38+
// l is a length of N in binary representation
39+
const l = Math.floor(Math.log(N) / Math.log(2)) + 1
40+
// bitmask has the same length as num and contains only ones 1...1
41+
const bitmask = (1 << l) - 1
42+
// flip all bits
43+
return bitmask ^ N
44+
}

0 commit comments

Comments
 (0)