Toggle all the bits of a number except k-th bit.
Given a positive (or unsigned) integer n, write a function to toggle all the bits except k-th bit. Here value of k starts from 0 (zero) and from right.
Examples:
Input : n = 4294967295, k = 0
Output : 1
The number 4294967295 in 32 bits has all bits
set. When we toggle all bits except last bit,
we get 1.
Input : n = 1, k = 1
Output : 4294967292
4294967262 has all bits toggled except second
bit from right.
- Toggle bit at k-th position. We do it by finding a number with only k-th bit set (using 1 << k), then doing bitwise XOR of this number n.
- Toggle all bits of number obtained above using ~ (Bitwise negation)
C++
#include <iostream>
using namespace std;
unsigned int toggleAllExceptK(unsigned int n,
unsigned int k)
{
return ~(n ^ (1 << k));
}
int main()
{
unsigned int n = 4294967295;
unsigned int k = 0;
cout << toggleAllExceptK(n, k);
return 0;
}
|
C
#include<stdio.h>
unsigned int toggleAllExceptK(unsigned int n,
unsigned int k)
{
return ~(n ^ (1 << k));
}
int main()
{
unsigned int n = 4294967295;
unsigned int k = 0;
printf ( "%u" , toggleAllExceptK( n, k));
return 0;
}
|
Java
public class Main {
public static long toggleAllExceptK( long n, int k) {
long temp = n ^ (1L << k);
long mask = (1L << 32 ) - 1 ;
return ~temp & mask;
}
public static void main(String[] args) {
long n = 4294967295L;
int k = 0 ;
System.out.println(toggleAllExceptK(n, k));
}
}
|
Python3
def toggleAllExceptK(n, k):
temp = bin (n ^ ( 1 << k))[ 2 :]
ans = ""
for i in temp:
if i = = '1' :
ans + = '0'
else :
ans + = '1'
return int (ans, 2 )
if __name__ = = '__main__' :
n = 4294967295
k = 0
print (toggleAllExceptK(n, k))
|
Javascript
<script>
function toggleAllExceptK(n,k)
{
return ~(n ^ (1 << k));
}
let n = 4294967295;
let k = 0;
document.write(toggleAllExceptK(n, k));
</script>
|
C#
using System;
public class Program
{
public static long toggleAllExceptK( long n, int k)
{
long temp = n ^ (1L << k);
long mask = (1L << 32) - 1;
return ~temp & mask;
}
public static void Main( string [] args)
{
long n = 4294967295L;
int k = 0;
Console.WriteLine(toggleAllExceptK(n, k));
}
}
|
Output:
1
Time Complexity : O(1)
Space Complexity : O(1)
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...