Skip to content

Commit e57af49

Browse files
committed
Power of two with bitwise operators
1 parent bdbd6ce commit e57af49

File tree

5 files changed

+22
-6
lines changed

5 files changed

+22
-6
lines changed

src/bitwise-operator-permissions/bitwise-operator-permissions.js

Whitespace-only changes.

src/bitwise-operator-permissions/bitwise-operator-permissions.test.js

Whitespace-only changes.

src/pirmal-numbers/primal-numbers.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,3 @@ export const isNumberPrimeMath = (num) => {
1919
}
2020
return true;
2121
};
22-
23-
console.log(isNumberPrimeMath(4));

src/power-of-two/power-of-two.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
// Problem: Is given number a power of two?
2-
// Time complexity: logarithmic O(log n)
32

4-
const isPowerOfTwo = (num) => {
3+
// Time complexity: logarithmic O(log n)
4+
export const isPowerOfTwo = (num) => {
55
if (num > 1 && num % 2 === 0) return isPowerOfTwo(num / 2);
66
if (num < 1) return false;
77
if (num === 1) return true;
88
if (num % 2 !== 0) return false;
99
};
1010

11-
export default isPowerOfTwo;
11+
// Utilizing bitwise operators
12+
// Binary number: 128 64 32 16 8 4 2 1
13+
// Converting number to binary number - using subtractions 75 -> 01001011
14+
export const isPowerOfTwoBitwise = (num) => {
15+
return num & (num - 1) ? false : true;
16+
};
17+

src/power-of-two/power-of-two.test.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import isPowerOfTwo from "./power-of-two";
1+
import { isPowerOfTwo, isPowerOfTwoBitwise } from "./power-of-two";
22

33
describe("Is number a power of two", () => {
44
test("Is 8 a power of two", () => {
@@ -11,3 +11,15 @@ describe("Is number a power of two", () => {
1111
expect(isPowerOfTwo(13)).toBe(false);
1212
});
1313
});
14+
15+
describe("Is number a power of two | Bitwise operator", () => {
16+
test("Is 8 a power of two", () => {
17+
expect(isPowerOfTwoBitwise(8)).toBe(true);
18+
});
19+
test("Is 24 a power of two", () => {
20+
expect(isPowerOfTwoBitwise(24)).toBe(false);
21+
});
22+
test("Is 13 a power of two", () => {
23+
expect(isPowerOfTwoBitwise(13)).toBe(false);
24+
});
25+
});

0 commit comments

Comments
 (0)