Dado un número no negativo n . El problema es establecer el bit no establecido más a la derecha en la representación binaria de n . Si no hay bits no configurados, simplemente deje el número como está.
Ejemplos:
Input : 21 Output : 23 (21)10 = (10101)2 Rightmost unset bit is at position 2(from right) as highlighted in the binary representation of 21. (23)10 = (10111)2 The bit at position 2 has been set. Input : 15 Output : 15
Enfoque: Los siguientes son los pasos:
- Si n = 0, devuelve 1.
- Si todos los bits de n están establecidos, devuelve n. Consulte esta publicación.
- De lo contrario, realice bit a bit no en el número dado (operación equivalente al complemento de 1). Sea num = ~n.
- Obtener la posición del bit establecido más a la derecha de num . Deje que la posición sea pos .
- Volver (1 << (pos – 1)) | norte _
C++
// C++ implementation to set the rightmost unset bit #include <bits/stdc++.h> using namespace std; // function to find the position // of rightmost set bit int getPosOfRightmostSetBit(int n) { return log2(n&-n)+1; } int setRightmostUnsetBit(int n) { // if n = 0, return 1 if (n == 0) return 1; // if all bits of 'n' are set if ((n & (n + 1)) == 0) return n; // position of rightmost unset bit in 'n' // passing ~n as argument int pos = getPosOfRightmostSetBit(~n); // set the bit at position 'pos' return ((1 << (pos - 1)) | n); } // Driver program to test above int main() { int n = 21; cout << setRightmostUnsetBit(n); return 0; }
Java
// Java implementation to set // the rightmost unset bit class GFG { // function to find the position // of rightmost set bit static int getPosOfRightmostSetBit(int n) { return (int)((Math.log10(n & -n)) / (Math.log10(2))) + 1; } static int setRightmostUnsetBit(int n) { // if n = 0, return 1 if (n == 0) return 1; // if all bits of 'n' are set if ((n & (n + 1)) == 0) return n; // position of rightmost unset bit in 'n' // passing ~n as argument int pos = getPosOfRightmostSetBit(~n); // set the bit at position 'pos' return ((1 << (pos - 1)) | n); } // Driver code public static void main(String arg[]) { int n = 21; System.out.print(setRightmostUnsetBit(n)); } } // This code is contributed by Anant Agarwal.
Python3
# Python3 implementation to # set the rightmost unset bit import math # function to find the position # of rightmost set bit def getPosOfRightmostSetBit(n): return int(math.log2(n&-n)+1) def setRightmostUnsetBit(n): # if n = 0, return 1 if (n == 0): return 1 # if all bits of 'n' are set if ((n & (n + 1)) == 0): return n # position of rightmost unset bit in 'n' # passing ~n as argument pos = getPosOfRightmostSetBit(~n) # set the bit at position 'pos' return ((1 << (pos - 1)) | n) # Driver code n = 21 print(setRightmostUnsetBit(n)) # This code is contributed # by Anant Agarwal.
C#
// C# implementation to set // the rightmost unset bit using System; class GFG{ // Function to find the position // of rightmost set bit static int getPosOfRightmostSetBit(int n) { return (int)((Math.Log10(n & -n)) / (Math.Log10(2))) + 1; } static int setRightmostUnsetBit(int n) { // If n = 0, return 1 if (n == 0) return 1; // If all bits of 'n' are set if ((n & (n + 1)) == 0) return n; // Position of rightmost unset bit in 'n' // passing ~n as argument int pos = getPosOfRightmostSetBit(~n); // Set the bit at position 'pos' return ((1 << (pos - 1)) | n); } // Driver code public static void Main(String []arg) { int n = 21; Console.Write(setRightmostUnsetBit(n)); } } // This code is contributed by shivanisinghss2110
Javascript
<script> // JavaScript implementation to set // the rightmost unset bit // function to find the position // of rightmost set bit function getPosOfRightmostSetBit(n) { return ((Math.log10(n & -n)) / (Math.log10(2))) + 1; } function setRightmostUnsetBit(n) { // if n = 0, return 1 if (n == 0) return 1; // if all bits of 'n' are set if ((n & (n + 1)) == 0) return n; // position of rightmost unset bit in 'n' // passing ~n as argument let pos = getPosOfRightmostSetBit(~n); // set the bit at position 'pos' return ((1 << (pos - 1)) | n); } // Driver code let n = 21; document.write(setRightmostUnsetBit(n)); // This code is contributed by unknown2108 </script>
Producción:
23
Implementación alternativa
La idea es usar Integer.toBinaryString()
C++
// C++ program to implement the approach #include <bits/stdc++.h> using namespace std; // function to binary string and remove // the leading zeroes string getBinary(int n) { string binary = bitset<32>(n).to_string(); binary.erase(0, binary.find_first_not_of('0')); return binary; } void setMostRightUnset(int a) { // will get a number with all set bits except the // first set bit int x = a ^ (a - 1); cout << getBinary(x) << endl; // We reduce it to the number with single 1's on // the position of first set bit in given number x = x & a; cout << getBinary(x) << endl; // Move x on right by one shift to make OR // operation and make first rightest unset bit 1 x = x >> 1; int b = a | x; cout << "before setting bit " << getBinary(a) << endl; cout << "after setting bit " << getBinary(b) << endl; } int main() { int a = 21; setMostRightUnset(a); return 0; } // This code is contributed by phasing17
Java
import java.io.*; import java.util.Scanner; public class SetMostRightUnsetBit { public static void main(String args[]) { int a = 21; setMostRightUnset(a); } private static void setMostRightUnset(int a) { // will get a number with all set bits except the // first set bit int x = a ^ (a - 1); System.out.println(Integer.toBinaryString(x)); // We reduce it to the number with single 1's on // the position of first set bit in given number x = x & a; System.out.println(Integer.toBinaryString(x)); // Move x on right by one shift to make OR // operation and make first rightest unset bit 1 x = x >> 1; int b = a | x; System.out.println("before setting bit " + Integer.toBinaryString(a)); System.out.println("after setting bit " + Integer.toBinaryString(b)); } }
Python3
def setMostRightUnset(a): # Will get a number with all set # bits except the first set bit x = a ^ (a - 1) print(bin(x)[2:]) # We reduce it to the number with # single 1's on the position of # first set bit in given number x = x & a print(bin(x)[2:]) # Move x on right by one shift to # make OR operation and make first # rightest unset bit 1 x = x >> 1 b = a | x print("before setting bit ", bin(a)[2:]) print("after setting bit ", bin(b)[2:]) # Driver Code if __name__ == '__main__': a = 21 setMostRightUnset(a) # This code is contributed by mohit kumar 29
C#
using System; class SetMostRightUnsetBit{ // Driver Code public static void Main(String []args) { int a = 21; setMostRightUnset(a); } private static void setMostRightUnset(int a) { // will get a number with all set bits // except the first set bit int x = a ^ (a - 1); Console.WriteLine(Convert.ToString(x)); // We reduce it to the number with single 1's on // the position of first set bit in given number x = x & a; Console.WriteLine(Convert.ToString(x)); // Move x on right by one shift to make OR // operation and make first rightest unset bit 1 x = x >> 1; int b = a | x; Console.WriteLine("before setting bit " + Convert.ToString(a, 2)); Console.WriteLine("after setting bit " + Convert.ToString(b, 2)); } } // This code is contributed by shivanisinghss2110
Javascript
<script> function setMostRightUnset(a) { // will get a number with all set bits except the // first set bit let x = a ^ (a - 1); document.write((x >>> 0).toString(2)+"<br>"); // We reduce it to the number with single 1's on // the position of first set bit in given number x = x & a; document.write((x >>> 0).toString(2)+"<br>"); // Move x on right by one shift to make OR // operation and make first rightest unset bit 1 x = x >> 1; let b = a | x; document.write("before setting bit " + (a >>> 0).toString(2)+"<br>"); document.write("after setting bit " + (b >>> 0).toString(2)+"<br>"); } let a = 21; setMostRightUnset(a); // This code is contributed by patel2127 </script>
Producción:
1 1 before setting bit 10101 after setting bit 10101
Otro enfoque:
La idea es x|(x+1) establece el bit no establecido más bajo (más a la derecha), pero puede establecer un bit cero inicial si el número dado no contiene ningún bit no establecido, por ejemplo
if all bits set 15 is 1111 = 00001111 16 is 10000 = 00010000 _________ x|(x+1) 00011111 on performing x|(x+1) it converts to 00011111 but here we should only consider only 1111 and return 1111 as there are no unset bits. else 13 is 1101 = 00001101 14 is 1110 = 00001110 _________ x|(x+1) 00001111 on performing x|(x+1) it converts to 00011111 which is required number.
Entonces podemos eliminar este tipo de operación redundante verificando si hay ceros en el número dado. Observamos solo el número cuyos bits establecidos son de la forma 2 k -1 no tienen bits no establecidos en ellos, por lo que al capturar estos números podemos realizar nuestra idea.
C++
// C++ implementation to set the rightmost unset bit #include <bits/stdc++.h> using namespace std; int setRightmostUnsetBit(int n) { // if all bits of 'n' are set // the number is of form 2^k -1 return n if (!(n & (n + 1))) return n; // else return n | (n + 1); } // Driver program to test above int main() { int n = 21; cout << setRightmostUnsetBit(n); return 0; } // This code is contributed by Kasina Dheeraj.
Java
// Java implementation to set // the rightmost unset bit class GFG { static int setRightmostUnsetBit(int n) { // if all bits of 'n' are set // the number is of form 2^k -1 return n if ((n & (n + 1)) == 0) return n; // else return n | (n + 1); } // Driver code public static void main(String arg[]) { int n = 21; System.out.print(setRightmostUnsetBit(n)); } } // This code is contributed by Kasina Dheeraj.
Python3
# Python3 implementation to # set the rightmost unset bit import math def setRightmostUnsetBit(n): # if all bits of 'n' are set # the number is of form 2^k -1 return n if ((n & (n + 1)) == 0): return n # else return n | (n+1) # Driver code n = 21 print(setRightmostUnsetBit(n)) # This code is contributed by Kasina Dheeraj.
C#
// C# implementation to set // the rightmost unset bit using System; class GFG { static int setRightmostUnsetBit(int n) { // if all bits of 'n' are set // the number is of form 2^k -1 return n if ((n & (n + 1)) == 0) return n; // else return n | (n + 1); } // Driver code public static void Main(String[] arg) { int n = 21; Console.Write(setRightmostUnsetBit(n)); } } // This code is contributed by Kasina Dheeraj.
Javascript
// JavaScript implementation to set the rightmost unset bit function setRightmostUnsetBit(n) { // if all bits of 'n' are set // the number is of form 2^k -1 return n if (!(n & (n + 1))) return n; // else return n | (n + 1); } // Driver program to test above let n = 21; console.log(setRightmostUnsetBit(n)); // This code is contributed by phasing17
Producción:
23
Complejidad del tiempo: O(1)
Complejidad espacial: O(1)
Este artículo es una contribución de Ayush Jauhari y Kasina Dheeraj . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA