Skip to content

Commit

Permalink
added algo for checking the number is power of four or not
Browse files Browse the repository at this point in the history
  • Loading branch information
madhuredra committed Sep 11, 2023
1 parent 00e40e6 commit 0e154ec
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Bit-Manipulation/IsPowerofFour.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
author: @dev-madhurendra
This script will check whether the given
number is a power of four or not.
A number will be power of four if and only if there is a 1 in the binary
of the digit and it will be at the first position
n n-1%3==0 (n-1)bin (n)bin
1 0 0 1 - 4^0
4 3 011 100 - 4^1
16 15 01111 10000 - 4^2
64 63 011111 1000000 - 4^3
a) There is only one bit set in the binary representation of n (or n is a power of 2)
b) There is only one bit unset in the n-1
c) And the and of n&n-1 will be 0
d) N-1 will be divisble by 3
*/

const IsPowerOfFour = (n) => ((n > 0) && ((n & n - 1) === 0) && (n % 3 === 1))

export { IsPowerOfFour }
14 changes: 14 additions & 0 deletions Bit-Manipulation/test/IsPowerOfFour.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { IsPowerOfFour } from '../IsPowerofFour'

describe('IsPowerOfFour', () => {
it.each([
[0, false],
[4, true],
[16, true],
[12, false],
[64, true],
[-64, false]
])('should return the number is power of four or not', (n, expected) => {
expect(IsPowerOfFour(n)).toBe(expected)
})
})

0 comments on commit 0e154ec

Please sign in to comment.