给定数字N,任务是清除此数字N的第K位。如果第K位为0,则将其设置为1,如果为1,则将其设置为0。
例子:
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.
方法:
- 由于未设置位和设置位的XOR会导致设置位,而已设置位和设置位的XOR会导致未设置位。因此,用设置的位对任何位执行按位XOR运算将导致该位的切换,即
Any bit
Set bit = Toggle which means, 0 ^ 1 = 1 1 ^ 1 = 0 - 因此,为了切换一位,最好将数字与复位位进行按位异或。
n = n ^ 1 << k OR n ^= 1 << k where k is the bit that is to be cleared
下面是上述方法的实现:
C
// C program to toggle K-th bit of a number N
#include
// Function to toggle the kth bit of n
int toggleBit(int n, int k)
{
return (n ^ (1 << (k - 1)));
}
// Driver code
int main()
{
int n = 5, k = 2;
printf("%d\n", toggleBit(n, k));
return 0;
}
Java
// Java program to toggle K-th bit of a number N
class GFG
{
// Function to toggle the kth bit of n
static int toggleBit(int n, int k)
{
return (n ^ (1 << (k - 1)));
}
// Driver code
public static void main(String []args)
{
int n = 5, k = 2;
System.out.printf("%d\n", toggleBit(n, k));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to clear K-th bit
# of a number N
# Function to toggle the kth bit of n
def toggleBit(n, k) :
return (n ^ (1 << (k - 1)));
# Driver code
if __name__ == "__main__" :
n = 5; k = 2;
print(toggleBit(n, k));
# This code is contributed by AnkitRai01
C#
// C# program to toggle K-th bit of a number N
using System;
class GFG
{
// Function to toggle the kth bit of n
static int toggleBit(int n, int k)
{
return (n ^ (1 << (k - 1)));
}
// Driver code
public static void Main(String []args)
{
int n = 5, k = 2;
Console.WriteLine("{0}", toggleBit(n, k));
}
}
// This code is contributed by PrinciRaj1992
输出:
7