Dado un número N, la tarea es borrar el K-ésimo bit de este número N. Si el K-ésimo bit es 0, configúrelo en 1 y si es 1, configúrelo en 0.
Ejemplos:
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.
Acercarse:
- Dado que XOR de un bit activado y desactivado da como resultado un bit activado y XOR de un bit activado y activado da como resultado un bit desactivado. Por lo tanto, realizar XOR bit a bit de cualquier bit con un bit establecido da como resultado un cambio de ese bit, es decir
Any bit <bitwise XOR> Set bit = Toggle which means, 0 ^ 1 = 1 1 ^ 1 = 0
- Entonces, para alternar un poco, la mejor idea es realizar un XOR 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 toggle K-th bit of a number N #include<bits/stdc++.h> using namespace std; // 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; cout << toggleBit(n, k) << endl; return 0; } // This code is contributed by noob2000
C
// C program to toggle K-th bit of a number N #include <stdio.h> // 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
Javascript
<script> // Javascript program to toggle K-th bit of a number N // Function to toggle the kth bit of n function toggleBit(n, k) { return (n ^ (1 << (k - 1))); } // Driver code var n = 5, k = 2; document.write( toggleBit(n, k)); // This code is contributed by famously. </script>
Producción:
7
Complejidad de tiempo: O(1)
Espacio Auxiliar: O(1)