给定正整数N ,任务是对C中N的二进制表示形式执行以下操作序列。
- 查找了一下:找到K的在N二进制表示个位。
- 设置一位:如果第K位为0 ,则将其设置为1 。否则,请保持不变。
- 清除位:如果第K位为1 ,则将其清除为0 。否则,请保持不变。
- 切换一位:如果第K位为1 ,则将其更改为0 ,反之亦然。
- 修改了一下:给定的位替换第K个位。
例子:
Input:N = 5, K = 1, P = 0
Output:
K(= 1)th bit of 5 is 1.
Setting the K(= 1)th bit modifies N to 5
Clearing the K(= 1)th bit modifies N to 4.
Toggling the K(= 1)th bit modifies N to 4.
Replacing the K(= 1)th bit with P(= 0) modifies N to 4
Input: N = 10, K = 2, P = 1
Output:
Kth(= 2) bit of 5 is 1.
Setting the K(= 2)th bit modifies N to 10.
Clearing the K(= 2)th bit modifies N to 8.
Toggling the K(= 2)th bit modifies N to 8.
Replacing the K(= 2)th bit with P(= 1) modifies N to 10.
方法:按照以下步骤查找,设置,清除,切换和修改N的二进制表示形式中的第K位。
发现一点:
(N >> K) & 1
设置一点:
N = N | (1 << K)
清除一点:
N = N & ~(1 << K)
切换一下:
N = N ^ (1 << K)
修改一下:
N = N | (P << K)
下面是上述方法的实现:
C
// C program to implement
// the above approach
#include
// Function to set the kth bit of n
int setBit(int n, int k)
{
return (n | (1 << (k - 1)));
}
// Function to clear the kth bit of n
int clearBit(int n, int k)
{
return (n & (~(1 << (k - 1))));
}
// Function to toggle the kth bit of n
int toggleBit(int n, int k)
{
return (n ^ (1 << (k - 1)));
}
// Function to modify k-th bit with p
int modifyBit(int n, int k, int p)
{
return (n | (p << k));
}
// Function to find the kth bit of n
int findBit(int n, int k)
{
return ((n >> k) & 1);
}
// Utility function to perform
// the specified Bit Operations
void bitOperations(int n, int k,
int p)
{
printf("K(= %d)-th bit of %d is %d\n",
k, n, findBit(n, k));
printf("Setting K(= %d)th bit modifies N to %d\n",
k, setBit(n, k));
printf("Clearing K(= %d)th bit modifies N to %d\n",
k, clearBit(n, k));
printf("Toggling K(= %d)th bit modifies N to %d\n",
k, toggleBit(n, k));
printf("Replacing the K(= %d)th bit", k);
printf(" with P(= %d) modifies N to 10\n",
modifyBit(n, k, p));
}
// Driver Code
int main()
{
int n = 5, k = 1, p = 1;
bitOperations(n, k, p);
return 0;
}
输出:
K(= 1)-th bit of 5 is 0
Setting K(= 1)th bit modifies N to 5
Clearing K(= 1)th bit modifies N to 4
Toggling K(= 1)th bit modifies N to 4
Replacing the K(= 1)th bit with P(= 7) modifies N to 10
时间复杂度: O(log(N))
辅助空间: O(1)