Dado un número N, la tarea es borrar el K-ésimo bit de este número N. Si el K-ésimo bit es 1, entonces límpielo a 0 y si es 0, déjelo sin cambios.
Ejemplos:
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.
Acercarse:
- Dado que AND bit a bit de cualquier bit con un bit de reinicio da como resultado un bit de reinicio, es decir
Any bit <bitwise AND> Reset bit = Reset bit which means, 0 & 0 = 0 1 & 0 = 0
- Entonces, para borrar un poco, la mejor idea es realizar un AND bit a bit del número con un bit de reinicio.
n = n & ~(1 << k) OR n &= ~(1 << k) where k is the bit that is to be cleared
A continuación se muestra la implementación del enfoque anterior:
C
// C program to clear K-th bit of a number N #include <stdio.h> // 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; }
C++
// C++ program to clear K-th bit of a number N #include <bits/stdc++.h> using namespace std; // 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; cout<<clearBit(n, k)<<endl; return 0; } // This code is contributed by rutvik_56.
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
Javascript
<script> // JavaScript program to clear K-th bit of a number N // Function to clear the kth bit of n function clearBit(n, k) { return (n & (~(1 << (k - 1)))); } // Driver code var n = 5, k = 1; document.write( clearBit(n, k)); </script>
Producción:
4
Complejidad de tiempo: O(1)
Espacio Auxiliar: O(1)