Set the K-th bit of a given number
Last Updated :
19 Jul, 2022
Given a number n and a value k. From the right, set the kth bit in the binary representation of n. The position of LSB(or last bit) is 0, second last bit is 1 and so on. Also, 0 <= k < x, where x is the number of bits in the binary representation of n.
Examples:
Input : n = 10, k = 2
Output : 14
(10)10 = (1010)2
Now, set the 2nd bit from right.
(14)10 = (1110)2
2nd bit has been set.
Input : n = 15, k = 3
Output : 15
3rd bit of 15 is already set.
To set any bit we use bitwise OR | operator. As we already know bitwise OR | operator evaluates each bit of the result to 1 if any of the operand’s corresponding bit is set (1). In-order to set kth bit of a number 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.
In general, (1 << k) | n.
C++
#include <bits/stdc++.h>
using namespace std;
int setKthBit( int n, int k)
{
return ((1 << k) | n);
}
int main()
{
int n = 10, k = 2;
cout << "Kth bit set number = "
<< setKthBit(n, k);
return 0;
}
|
Java
class GFG {
static int setKthBit( int n, int k)
{
return (( 1 << k) | n);
}
public static void main(String arg[])
{
int n = 10 , k = 2 ;
System.out.print( "Kth bit set number = " +
setKthBit(n, k));
}
}
|
Python3
def setKthBit(n,k):
return (( 1 << k) | n)
n = 10
k = 2
print ( "Kth bit set number = " ,
setKthBit(n, k))
|
C#
using System;
class GFG {
static int setKthBit( int n, int k)
{
return ((1 << k) | n);
}
public static void Main()
{
int n = 10, k = 2;
Console.Write( "Kth bit set number = "
+ setKthBit(n, k));
}
}
|
PHP
<?php
function setKthBit( $n , $k )
{
return ((1 << $k ) | $n );
}
$n = 10; $k = 2;
echo "Kth bit set number = " ,
setKthBit( $n , $k );
?>
|
Javascript
<script>
function setKthBit(n, k)
{
return ((1 << k) | n);
}
let n = 10, k = 2;
document.write( "Kth bit set number = " + setKthBit(n, k));
</script>
|
Output:
Kth bit set number = 14
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...