Toggling k-th bit of a number
For a given number n, if k-th bit is 0, then toggle it to 1 and if it is 1 then, toggle it to 0.
Examples :
Input : n = 5, k = 1
Output : 4
5 is represented as 101 in binary
and has its first bit 1, so toggling
it will result in 100 i.e. 4.
Input : n = 2, k = 3
Output : 6
Input : n = 75, k = 4
Output : 67
Below are simple steps to find the value of k-th bit
1) Left shift given number 1 by k-1 to create
a number that has only set bit as k-th bit.
temp = 1 << (k-1)
2) Return bitwise XOR of temp and n. Since temp
has only k-th bit set, doing XOR would toggle
only this bit.
Example :
n = 75 and k = 4
temp = 1 << (k-1) = 1 << 3 = 8
Binary Representation of temp = 0..00001000
Binary Representation of n = 0..01001011
Bitwise XOR of two numbers = 0..01000011
C++
#include<iostream>
using namespace std;
int toggleKthBit( int n, int k)
{
return (n ^ (1 << (k-1)));
}
int main()
{
int n = 5, k = 1;
cout << toggleKthBit(n , k);
return 0;
}
|
Java
class Toggle
{
static int toggleKthBit( int n, int k)
{
return (n ^ ( 1 << (k- 1 )));
}
public static void main (String[] args)
{
int n = 5 , k = 1 ;
System.out.println(toggleKthBit(n , k));
}
}
|
Python3
def toggleKthBit(n, k):
return (n ^ ( 1 << (k - 1 )))
n = 5
k = 1
print ( toggleKthBit(n , k))
|
C#
using System;
class GFG {
static int toggleKthBit( int n, int k)
{
return (n ^ (1 << (k-1)));
}
public static void Main()
{
int n = 5, k = 1;
Console.WriteLine(toggleKthBit(n , k));
}
}
|
PHP
<?php
function toggleKthBit( $n , $k )
{
return ( $n ^ (1 << ( $k - 1)));
}
$n = 5;
$k = 1;
echo toggleKthBit( $n , $k );
?>
|
Javascript
<script>
function toggleKthBit(n, k)
{
return (n ^ (1 << (k-1)));
}
let n = 5, k = 1;
document.write(toggleKthBit(n , k));
</script>
|
Output :
4
Time Complexity : O(1)
Space Complexity : O(1)
If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...