📜  程序清除数字N的第K位

📅  最后修改于: 2021-05-05 01:39:42             🧑  作者: Mango

给定数字N,任务是清除此数字N的第K位。如果第K位为1,则将其清除为0,如果为0,则将其保持不变。

例子:

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

Input: N = 5, K = 2
Output: 5
5 is represented as 101 in binary
and has its second bit is already 0,
so clearing it will result in 101 i.e. 5.

方法:

  • 由于任何位与复位位的按位与运算都会导致复位位,即
    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
    

下面是上述方法的实现:

C
// C program to clear K-th bit of a number N
  
#include 
  
// Function to clear the kth bit of n
int clearBit(int n, int k)
{
    return (n & (~(1 << (k - 1))));
}
  
// Driver code
int main()
{
    int n = 5, k = 1;
  
    printf("%d\n", clearBit(n, k));
  
    return 0;
}


Python3
# Python3 program to clear
# K-th bit of a number N
  
# Function to clear the kth bit of n
def clearBit(n, k):
    return (n & ( ~(1 << (k - 1))))
  
# Driver code
n = 5
k = 1
  
print(clearBit(n, k))
  
# This code is contributed 
# by Mohit Kumar


Java
// Java program to clear K-th bit of a number N 
class GFG 
{
      
    // Function to clear the kth bit of n 
    static int clearBit(int n, int k) 
    { 
        return (n & (~(1 << (k - 1)))); 
    } 
      
    // Driver code 
    public static void main (String[] args) 
    { 
        int n = 5, k = 1; 
      
        System.out.println(clearBit(n, k)); 
    } 
}
  
// This code is contributed by AnkitRai01


C#
// C# program to clear K-th bit of a number N 
using System;
  
class GFG 
{
      
    // Function to clear the kth bit of n 
    static int clearBit(int n, int k) 
    { 
        return (n & (~(1 << (k - 1)))); 
    } 
      
    // Driver code 
    public static void Main (String[] args) 
    { 
        int n = 5, k = 1; 
      
        Console.WriteLine(clearBit(n, k)); 
    } 
}
  
// This code is contributed by PrinciRaj1992


输出:
4