mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
chore: Merge PR #632 from AbhinavXT/master
Added SetBit.js, SetBit.test.js in Bit-Manipulation directory
This commit is contained in:
31
Bit-Manipulation/SetBit.js
Normal file
31
Bit-Manipulation/SetBit.js
Normal file
@ -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
Bit-Manipulation/test/SetBit.test.js
Normal file
21
Bit-Manipulation/test/SetBit.test.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { setBit } from '../SetBit'
|
||||
|
||||
test('Set bit number 0 in 1:', () => {
|
||||
const setBitPos = setBit(1, 0)
|
||||
expect(setBitPos).toBe(1)
|
||||
})
|
||||
|
||||
test('Set bit number 0 in 2:', () => {
|
||||
const setBitPos = setBit(2, 0)
|
||||
expect(setBitPos).toBe(3)
|
||||
})
|
||||
|
||||
test('Set bit number 1 in 10:', () => {
|
||||
const setBitPos = setBit(10, 1)
|
||||
expect(setBitPos).toBe(10)
|
||||
})
|
||||
|
||||
test('Set bit number 2 in 10:', () => {
|
||||
const setBitPos = setBit(10, 2)
|
||||
expect(setBitPos).toBe(14)
|
||||
})
|
Reference in New Issue
Block a user