JavaScript Program to Set a Particular Bit in a Number

Setting a specific bit at a given position within a number using JavaScript involves manipulating the binary representation of the number to ensure that a particular bit is turned on set to 1.

Examples:

Input : 
n = 10, k = 2
Output :
14

Approach

  • The variable “bitPosition” determines the index of the bit to be set, starting from 0.
  • A bit mask is created using left shift (‘<<‘), resulting in a mask like “00000100” for ‘bitPosition = 2’.
  • The variable “n” is assigned a decimal value, such as “10”, which corresponds to its binary representation “00001010”.
  • Bitwise OR (‘|’) operation is applied between ‘n’ and the mask to set the specified bit to 1, leaving other bits unchanged.
  • The output will be 14, representing the decimal equivalent of the binary number with the specified bit set.

Example: The example below shows how to set a particular bit in a number using JavaScript.

JavaScript
// Define the bit position to set (0-based index)
let bitPosition = 2; // 3rd bit (0-based index)

// Create a bit mask with only the desired bit set to 1
// This creates a mask like 00000100 (for bitPosition=2)
let mask = 1 << bitPosition; 

// Binary: 00001010
let n = 10; 

// Set the specified bit using bitwise OR
n |= mask; // Binary: 00001010 | 00000100 = 00001110 (14 in decimal)
console.log(n);

Output
14

Time Complexity: O(1).

Space Complexity: O(1).