Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Bit-Manipulation/SetBit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Setting Bit: https://www.geeksforgeeks.org/set-k-th-bit-given-number/
*
* To set any bit we use bitwise OR (|) operator.
*
* Bitwise OR (|) compares the bits of the 32
* bit binary representations of the number and
* returns a number after comparing each bit.
*
* 0 | 0 -> 0
* 0 | 1 -> 1
* 1 | 0 -> 1
* 1 | 1 -> 1
*
* In-order to set kth bit of a number (where k is the position where bit is to be changed)
* we need to shift 1 k times to its left and then perform bitwise OR operation with the
* number and result of left shift performed just before.
*
* References:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR
*/

/**
* @param {number} number
* @param {number} bitPosition - zero based.
* @return {number}
*/

export const setBit = (number, bitPosition) => {
return number | (1 << bitPosition)
}
21 changes: 21 additions & 0 deletions Bit-Manipulation/test/SetBit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { setBit } from '../SetBit'

test('should set bit at the given bit Position', () => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expand the test message a bit to give as much information as possible.
Here:

Suggested change
test('should set bit at the given bit Position', () => {
test('Set bit number 0 in 1:', () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add this for all the tests.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AbhinavXT Do not apply the same name to all of them, replace the 0 and 1 with the bit number and the number respectively.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, Sorry about that. I will correct the changes.

const setBitPos = setBit(1, 0)
expect(setBitPos).toBe(1)
})

test('should set bit at the given bit Position', () => {
const setBitPos = setBit(1, 0)
expect(setBitPos).toBe(1)
})

test('should set bit at the given bit Position', () => {
const setBitPos = setBit(10, 1)
expect(setBitPos).toBe(10)
})

test('should set bit at the given bit Position', () => {
const setBitPos = setBit(10, 2)
expect(setBitPos).toBe(14)
})