mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2026-03-13 15:21:15 +08:00
Add code and tests for checking power of 2
This commit is contained in:
17
Bit-Manipulation/IsPowerOfTwo.js
Normal file
17
Bit-Manipulation/IsPowerOfTwo.js
Normal file
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
author: @Aayushi-Mittal
|
||||
|
||||
This script will check whether the given
|
||||
number is a power of two or not.
|
||||
|
||||
*/
|
||||
|
||||
export const IsPowerOfTwo = (n) => {
|
||||
if ((n&(n-1))==0 && n!=0)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
// console.log(IsPowerOfTwo(0));
|
||||
|
||||
21
Bit-Manipulation/test/IsPowerOfTwo.test.js
Normal file
21
Bit-Manipulation/test/IsPowerOfTwo.test.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import {IsPowerOfTwo} from '../IsPowerOfTwo'
|
||||
|
||||
test('Check if 0 is a power of 2 or not:', () => {
|
||||
const res = IsPowerOfTwo(1, 0)
|
||||
expect(res).toBe(false)
|
||||
})
|
||||
|
||||
test('Check if 4 is a power of 2 or not:', () => {
|
||||
const res = IsPowerOfTwo(4)
|
||||
expect(res).toBe(true)
|
||||
})
|
||||
|
||||
test('Check if 1024 is a power of 2 or not:', () => {
|
||||
const res = IsPowerOfTwo(1024)
|
||||
expect(res).toBe(true)
|
||||
})
|
||||
|
||||
test('Check if 1025 is a power of 2 or not:', () => {
|
||||
const res = IsPowerOfTwo(1025)
|
||||
expect(res).toBe(false)
|
||||
})
|
||||
Reference in New Issue
Block a user