Skip to content

Commit 51a9126

Browse files
committed
Added SetBit.js, SetBit.test.js in Bit-Manipulation directory
1 parent 709de83 commit 51a9126

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Bit-Manipulation/SetBit.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Setting Bit: https://www.geeksforgeeks.org/set-k-th-bit-given-number/
3+
*
4+
* To set any bit we use bitwise OR (|) operator.
5+
*
6+
* Bitwise OR (|) compares the bits of the 32
7+
* bit binary representations of the number and
8+
* returns a number after comparing each bit.
9+
*
10+
* 0 | 0 -> 0
11+
* 0 | 1 -> 1
12+
* 1 | 0 -> 1
13+
* 1 | 1 -> 1
14+
*
15+
* In-order to set kth bit of a number (where k is the position where bit is to be changed)
16+
* we need to shift 1 k times to its left and then perform bitwise OR operation with the
17+
* number and result of left shift performed just before.
18+
*
19+
* References:
20+
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR
21+
*/
22+
23+
/**
24+
* @param {number} number
25+
* @param {number} bitPosition - zero based.
26+
* @return {number}
27+
*/
28+
29+
export const setBit = (number, bitPosition) => {
30+
return number | (1 << bitPosition)
31+
}

Bit-Manipulation/test/SetBit.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { setBit } from '../SetBit'
2+
3+
test('should set bit at the given bit Position', () => {
4+
const setBitPos = setBit(1, 0)
5+
expect(setBitPos).toBe(1)
6+
})
7+
8+
test('should set bit at the given bit Position', () => {
9+
const setBitPos = setBit(1, 0)
10+
expect(setBitPos).toBe(1)
11+
})
12+
13+
test('should set bit at the given bit Position', () => {
14+
const setBitPos = setBit(10, 1)
15+
expect(setBitPos).toBe(10)
16+
})
17+
18+
test('should set bit at the given bit Position', () => {
19+
const setBitPos = setBit(10, 2)
20+
expect(setBitPos).toBe(14)
21+
})

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