📜  在C中设置,清除和切换数字的给定位

📅  最后修改于: 2021-05-28 04:00:07             🧑  作者: Mango

给定数字N,任务是设置,清除和切换此数字N的第K位。

  • 设置一位意味着,如果第K位为0,则将其设置为1,如果为1,则将其保持不变。
  • 清除一位意味着,如果第K位为1,则将其清除为0,如果为0,则将其保持不变。
  • 切换一位意味着,如果第K位为1,则将其更改为0,如果为0,则将其更改为1。

例子:

Input: N = 5, K = 1
Output: 
Setting Kth bit: 5
Clearing Kth bit: 4
Toggling Kth bit: 4
Explanation: 
5 is represented as 101 in binary
and has its first bit 1, so 
setting it will result in 101 i.e. 5.
clearing it will result in 100 i.e. 4.
toggling it will result in 100 i.e. 4.

Input: N = 7, K = 2
Output: 
Setting Kth bit: 7
Clearing Kth bit: 5
Toggling Kth bit: 5
Explanation: 
7 is represented as 111 in binary
and has its second bit 1, so 
setting it will result in 111 i.e. 7.
clearing it will result in 101 i.e. 5.
toggling it will result in 101 i.e. 5.

方法:

以下是设置,清除和切换N的第K位的步骤:

设置一点

  • 既然我们都知道,对某个位与一个设置的位进行按位“或”运算就得到一个设置的位,即
    Any bit  Set bit = Set bit
    
    which means,
    0 | 1 = 1
    1 | 1 = 1
    
  • 因此,对于设置位,最好将数字与设置的位进行按位“或”运算。
    N = N | 1 << K
    OR
    N |= 1 << K
    
    where K is the bit that is to be set
    

清除一点

  • 由于任何位与复位位的按位与运算都会导致复位位,即
    Any bit  Reset bit = Reset bit
    
    which means,
    0 & 0 = 0
    1 & 0 = 0
    
    
    
        
  • 因此,为了清除位,最好将数字与复位位进行按位与运算。
    n = n & ~(1 << k)
    OR
    n &= ~(1 << k)
    
    where k is the bit that is to be cleared
    

切换一下

  • 由于未设置位和设置位的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 program to set, clear and toggle a bit
  
#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)));
}
  
// Driver code
int main()
{
    int n = 5, k = 1;
  
    printf("%d with %d-th bit Set: %d\n",
           n, k, setBit(n, k));
    printf("%d with %d-th bit Cleared: %d\n",
           n, k, clearBit(n, k));
    printf("%d with %d-th bit Toggled: %d\n",
           n, k, toggleBit(n, k));
    return 0;
}
输出:
5 with 1-th bit Set: 5
5 with 1-th bit Cleared: 4
5 with 1-th bit Toggled: 4

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。