Add Set Kth Bit (#4990)

This commit is contained in:
Nishant Jain
2024-01-02 23:48:01 +05:30
committed by GitHub
parent 7ece806cf5
commit a7d140a43e
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.thealgorithms.bitmanipulation;
/***
* Sets the kth bit of a given integer to 1
* e.g. setting 3rd bit in binary of 17 (binary 10001) gives 25 (binary 11001)
* @author inishantjain
*/
public class SetKthBit {
/**
* Sets the kth bit of a given integer.
*
* @param num The original integer.
* @param k The position of the bit to set (0-based index).
* @return The integer with the kth bit set.
*/
public static int setKthBit(int num, int k) {
int mask = 1 << k;
num = num | mask;
return num;
}
}