Skip to content

Commit 0e154ec

Browse files
author
madhuredra
committed
added algo for checking the number is power of four or not
1 parent 00e40e6 commit 0e154ec

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Bit-Manipulation/IsPowerofFour.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
author: @dev-madhurendra
3+
4+
This script will check whether the given
5+
number is a power of four or not.
6+
7+
A number will be power of four if and only if there is a 1 in the binary
8+
of the digit and it will be at the first position
9+
10+
n n-1%3==0 (n-1)bin (n)bin
11+
1 0 0 1 - 4^0
12+
4 3 011 100 - 4^1
13+
16 15 01111 10000 - 4^2
14+
64 63 011111 1000000 - 4^3
15+
16+
a) There is only one bit set in the binary representation of n (or n is a power of 2)
17+
b) There is only one bit unset in the n-1
18+
c) And the and of n&n-1 will be 0
19+
d) N-1 will be divisble by 3
20+
*/
21+
22+
const IsPowerOfFour = (n) => ((n > 0) && ((n & n - 1) === 0) && (n % 3 === 1))
23+
24+
export { IsPowerOfFour }
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { IsPowerOfFour } from '../IsPowerofFour'
2+
3+
describe('IsPowerOfFour', () => {
4+
it.each([
5+
[0, false],
6+
[4, true],
7+
[16, true],
8+
[12, false],
9+
[64, true],
10+
[-64, false]
11+
])('should return the number is power of four or not', (n, expected) => {
12+
expect(IsPowerOfFour(n)).toBe(expected)
13+
})
14+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy