Program to toggle K-th bit of a number N
Last Updated :
08 Nov, 2021
Given a number N, the task is to clear the K-th bit of this number N. If K-th bit is 0, then set it to 1 and if it is 1 then set it to 0.
Examples:
Input: N = 5, K = 2
Output: 7
5 is represented as 101 in binary
and has its second bit 0, so toggling
it will result in 111 i.e. 7.
Input: N = 5, K = 1
Output: 4
5 is represented as 101 in binary
and has its first bit is 1, so toggling
it will result in 100 i.e. 4.
Approach:
- Since XOR of unset and set bit results in a set bit and XOR of a set and set bit results in an unset bit. Hence performing bitwise XOR of any bit with a set bit results in toggle of that bit, i.e.
Any bit <bitwise XOR> Set bit = Toggle
which means,
0 ^ 1 = 1
1 ^ 1 = 0
- So in order to toggle a bit, performing a bitwise XOR of the number with a reset bit is the best idea.
n = n ^ 1 << k
OR
n ^= 1 << k
where k is the bit that is to be cleared
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int toggleBit( int n, int k)
{
return (n ^ (1 << (k - 1)));
}
int main()
{
int n = 5, k = 2;
cout << toggleBit(n, k) << endl;
return 0;
}
|
C
#include <stdio.h>
int toggleBit( int n, int k)
{
return (n ^ (1 << (k - 1)));
}
int main()
{
int n = 5, k = 2;
printf ( "%d\n" , toggleBit(n, k));
return 0;
}
|
Java
class GFG
{
static int toggleBit( int n, int k)
{
return (n ^ ( 1 << (k - 1 )));
}
public static void main(String []args)
{
int n = 5 , k = 2 ;
System.out.printf( "%d\n" , toggleBit(n, k));
}
}
|
Python3
def toggleBit(n, k) :
return (n ^ ( 1 << (k - 1 )));
if __name__ = = "__main__" :
n = 5 ; k = 2 ;
print (toggleBit(n, k));
|
C#
using System;
class GFG
{
static int toggleBit( int n, int k)
{
return (n ^ (1 << (k - 1)));
}
public static void Main(String []args)
{
int n = 5, k = 2;
Console.WriteLine( "{0}" , toggleBit(n, k));
}
}
|
Javascript
<script>
function toggleBit(n, k)
{
return (n ^ (1 << (k - 1)));
}
var n = 5, k = 2;
document.write( toggleBit(n, k));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...