How to turn on a particular bit in a number?
Last Updated :
05 May, 2021
Given a number n and a value k, turn on the k’th bit in n.
Examples:
Input: n = 4, k = 2
Output: 6
Input: n = 3, k = 3
Output: 7
Input: n = 64, k = 4
Output: 72
Input: n = 64, k = 5
Output: 80
The idea is to use bitwise << and | operators. Using expression “(1 << (k – 1))“, we get a number which has all bits unset, except the k’th bit. If we do bitwise | of this expression with n, we get a number which has all bits same as n except the k’th bit which is 1.
Below is the implementation of above idea.
C++
#include <iostream>
using namespace std;
int turnOnK( int n, int k)
{
if (k <= 0)
return n;
return (n | (1 << (k - 1)));
}
int main()
{
int n = 4;
int k = 2;
cout << turnOnK(n, k);
return 0;
}
|
Java
class GFG {
static int turnOnK( int n, int k)
{
if (k <= 0 )
return n;
return (n | ( 1 << (k - 1 )));
}
public static void main(String [] args)
{
int n = 4 ;
int k = 2 ;
System.out.print(turnOnK(n, k));
}
}
|
Python 3
def turnOnK(n, k):
if (k < = 0 ):
return n
return (n | ( 1 << (k - 1 )))
n = 4
k = 2
print (turnOnK(n, k))
|
C#
using System;
class GFG {
static int turnOnK( int n, int k)
{
if (k <= 0)
return n;
return (n | (1 << (k - 1)));
}
public static void Main()
{
int n = 4;
int k = 2;
Console.Write(turnOnK(n, k));
}
}
|
PHP
<?php
function turnOnK( $n , $k )
{
if ( $k <= 0)
return $n ;
return ( $n | (1 << ( $k - 1)));
}
$n = 4;
$k = 2;
echo turnOnK( $n , $k );
?>
|
Javascript
<script>
function turnOnK(n, k)
{
if (k <= 0)
return n;
return (n | (1 << (k - 1)));
}
let n = 4;
let k = 2;
document.write(turnOnK(n, k));
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...