Comprobar si todos los bits de un número están configurados

Dado un número n . El problema es verificar si cada bit en la representación binaria del número dado está configurado o no. Aquí 0 <= n .
Ejemplos: 

Input : 7
Output : Yes
(7)10 = (111)2

Input : 14
Output : No

Método 1: si n = 0, la respuesta es ‘No’. De lo contrario, realice las dos operaciones hasta que n se convierta en 0. 

While (n > 0)
 If n & 1 == 0, 
     return 'No'
 n >> 1

Si el ciclo termina sin devolver ‘No’, entonces todos los bits se establecen en la representación binaria de n

C++

// C++ implementation to check whether every digit in the
// binary representation of the given number is set or not
#include <bits/stdc++.h>
using namespace std;
 
// function to check if all the bits are set or not in the
// binary representation of 'n'
string areAllBitsSet(int n)
{
    // all bits are not set
    if (n == 0)
        return "No";
    // loop till n becomes '0'
    while (n > 0) {
        // if the last bit is not set
        if ((n & 1) == 0)
            return "No";
        // right shift 'n' by 1
        n = n >> 1;
    }
    // all bits are set
    return "Yes";
}
 
// Driver program to test above
int main()
{
    int n = 7;
    cout << areAllBitsSet(n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)

C

// C implementation to check whether every digit in the
// binary representation of the given number is set or not
#include <stdio.h>
 
// function to check if all the bits are set or not in the
// binary representation of 'n'
void areAllBitsSet(int n)
{
    // all bits are not set
    if (n == 0)
        printf("No");
    // loop till n becomes '0'
    while (n > 0) {
        // if the last bit is not set
        if ((n & 1) == 0)
            printf("No");
        // right shift 'n' by 1
        n = n >> 1;
    }
    // all bits are set
    printf("Yes");
}
 
// Driver program to test above
int main()
{
    int n = 7;
    areAllBitsSet(n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)

Java

// java implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
import java.io.*;
 
class GFG {
     
    // function to check if all the bits
    // are setthe bits are set or not
    // in the binary representation of 'n'
    static String areAllBitsSet(int n)
    {
        // all bits are not set
        if (n == 0)
            return "No";
     
        // loop till n becomes '0'
        while (n > 0)
        {
            // if the last bit is not set
            if ((n & 1) == 0)
                return "No";
     
            // right shift 'n' by 1
            n = n >> 1;
        }
     
            // all bits are set
            return "Yes";
    }
     
    // Driver program to test above
    public static void main (String[] args) {
    int n = 7;
     
    System.out.println(areAllBitsSet(n));
    }
}
 
 
// This code is contributed by vt_m

Python3

# Python implementation
# to check whether every
# digit in the binary
# representation of the
# given number is set or not
 
# function to check if
# all the bits are set
# or not in the binary
# representation of 'n'
def areAllBitsSet(n):
 
    # all bits are not set
    if (n == 0):
        return "No"
  
    # loop till n becomes '0'
    while (n > 0):
     
        # if the last bit is not set
        if ((n & 1) == 0):
            return "No"
  
        # right shift 'n' by 1
        n = n >> 1
     
  
    # all bits are set
    return "Yes"
 
  
# Driver program to test above
 
n = 7
print(areAllBitsSet(n))
 
# This code is contributed
# by Anant Agarwal.

C#

// C# implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
using System;
 
class GFG
{
     
    // function to check if 
    // all the bits are set
    // or not in the binary
    // representation of 'n'
    static String areAllBitsSet(int n)
    {
        // all bits are not set
        if (n == 0)
            return "No";
     
        // loop till n becomes '0'
        while (n > 0)
        {
            // if the last bit
            // is not set
            if ((n & 1) == 0)
                return "No";
     
            // right shift 'n' by 1
            n = n >> 1;
        }
     
            // all bits are set
            return "Yes";
    }
     
    // Driver Code
    static public void Main ()
    {
        int n = 7;
        Console.WriteLine(areAllBitsSet(n));
    }
}
 
// This code is contributed by ajit

PHP

<?php
// PHP implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
 
// function to check if all the
// bits are set or not in the
// binary representation of 'n'
function areAllBitsSet($n)
{
    // all bits are not set
    if ($n == 0)
        return "No";
 
    // loop till n becomes '0'
    while ($n > 0)
    {
        // if the last bit is not set
        if (($n & 1) == 0)
            return "No";
 
        // right shift 'n' by 1
        $n = $n >> 1;
    }
 
    // all bits are set
    return "Yes";
}
 
// Driver Code
$n = 7;
echo areAllBitsSet($n);
 
// This code is contributed by aj_36
?>

Javascript

<script>
 
// javascript implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
    
// function to check if all the bits
// are setthe bits are set or not
// in the binary representation of 'n'
function areAllBitsSet(n)
{
    // all bits are not set
    if (n == 0)
        return "No";
 
    // loop till n becomes '0'
    while (n > 0)
    {
        // if the last bit is not set
        if ((n & 1) == 0)
            return "No";
 
        // right shift 'n' by 1
        n = n >> 1;
    }
 
        // all bits are set
        return "Yes";
}
     
// Driver program to test above
var n = 7;
document.write(areAllBitsSet(n));
 
// This code contributed by Princi Singh
 
</script>

Producción : 
 

Yes

Complejidad de tiempo: O(d), donde ‘d’ es el número de bits en la representación binaria de n .
Espacio auxiliar:  O(1)
 
Método 2: Si n = 0, la respuesta es ‘No’. De lo contrario, agregue 1 a n . Sea num = n + 1. Si num & (num – 1) == 0, entonces todos los bits están configurados, de lo contrario, todos los bits no están configurados. 
Explicación: si todos los bits en la representación binaria de n están configurados, agregarle ‘1’ producirá un número que será una potencia perfecta de 2. Ahora, verifique si el nuevo número es una potencia perfecta de 2 o no. 
 

C++

// C++ implementation to check whether every
// digit in the binary representation of the
// given number is set or not
#include <bits/stdc++.h>
using namespace std;
 
// function to check if all the bits are set
// or not in the binary representation of 'n'
string areAllBitsSet(int n)
{
    // all bits are not set
    if (n == 0)
        return "No";
 
    // if true, then all bits are set
    if (((n + 1) & n) == 0)
        return "Yes";
 
    // else all bits are not set
    return "No";
}
 
// Driver program to test above
int main()
{
    int n = 7;
    cout << areAllBitsSet(n);
    return 0;
}

Java

// JAVA implementation to check whether
// every digit in the binary representation
// of the given number is set or not
import java.io.*;
 
class GFG {
     
    // function to check if all the
    // bits are set or not in the
    // binary representation of 'n'
    static String areAllBitsSet(int n)
    {
        // all bits are not set
        if (n == 0)
            return "No";
     
        // if true, then all bits are set
        if (((n + 1) & n) == 0)
            return "Yes";
     
        // else all bits are not set
        return "No";
    }
     
    // Driver program to test above
    public static void main (String[] args) {
    int n = 7;
    System.out.println(areAllBitsSet(n));
    }
}
 
// This code is contributed by vt_m

Python3

# Python implementation to
# check whether every
# digit in the binary
# representation of the
# given number is set or not
 
# function to check if
# all the bits are set
# or not in the binary
# representation of 'n'
def areAllBitsSet(n):
 
    # all bits are not set
    if (n == 0):
        return "No"
  
    # if true, then all bits are set
    if (((n + 1) & n) == 0):
        return "Yes"
  
    # else all bits are not set
    return "No"
 
  
# Driver program to test above
 
n = 7
print(areAllBitsSet(n))
 
# This code is contributed
# by Anant Agarwal.

C#

// C# implementation to check
// whether every digit in the
// binary representation of
// the given number is set or not
using System;
 
class GFG
{
     
    // function to check if all the
    // bits are set or not in the
    // binary representation of 'n'
    static String areAllBitsSet(int n)
    {
        // all bits are not set
        if (n == 0)
            return "No";
     
        // if true, then all
        // bits are set
        if (((n + 1) & n) == 0)
            return "Yes";
     
        // else all bits are not set
        return "No";
    }
     
    // Driver Code
    static public void Main ()
    {
        int n = 7;
        Console.WriteLine(areAllBitsSet(n));
    }
}
 
// This code is contributed by m_kit

PHP

<?php
// PHP implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
 
// function to check if all
// the bits are set or not in
// the binary representation of 'n'
function areAllBitsSet($n)
{
    // all bits are not set
    if ($n == 0)
        return "No";
 
    // if true, then all
    // bits are set
    if ((($n + 1) & $n) == 0)
        return "Yes";
 
    // else all bits
    // are not set
    return "No";
}
 
// Driver Code
$n = 7;
echo areAllBitsSet($n);
 
// This code is contributed by ajit
?>

Javascript

<script>
// javascript implementation to check whether
// every digit in the binary representation
// of the given number is set or not
    
// function to check if all the
// bits are set or not in the
// binary representation of 'n'
function areAllBitsSet(n)
{
    // all bits are not set
    if (n == 0)
        return "No";
 
    // if true, then all bits are set
    if (((n + 1) & n) == 0)
        return "Yes";
 
    // else all bits are not set
    return "No";
}
 
// Driver program to test above
var n = 7;
document.write(areAllBitsSet(n));
 
// This code contributed by Princi Singh
</script>
Producción

Yes

Tiempo Complejidad: O(1)
Espacio Auxiliar:  O(1)

Método 3 : simplemente podemos contar los bits establecidos totales presentes en la representación binaria del número y, en función de esto, podemos verificar si el número es igual a pow (2, __builtin_popcount (n)). Si resulta ser igual, devolvemos 1, de lo contrario devolvemos 0;

C++

#include <bits/stdc++.h>
using namespace std;
 
void isBitSet(int N)
{
    if (N == pow(2, __builtin_popcount(N)) - 1)
        cout << "Yes\n";
    else cout << "No\n";
}
 
int main()
{
    int N = 7;
    isBitSet(N);
    return 0;
}

Java

import java.util.*;
 
class GFG{
 
static void isBitSet(int N)
{
    if (N == Math.pow(2, Integer.bitCount(N)) - 1)
        System.out.print("Yes\n");
    else System.out.print("No\n");
}
 
public static void main(String[] args)
{
    int N = 7;
    isBitSet(N);
}
}
 
// This code is contributed by umadevi9616

Python3

def bitCount(n):
    n = n - ((n >> 1) & 0x55555555);
    n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
    return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
 
 
def isBitSet(N):
    if (N == pow(2, bitCount(N)) - 1):
        print("Yes");
    else:
        print("No");
 
 
if __name__ == '__main__':
    N = 7;
    isBitSet(N);
     
# This code is contributed by gauravrajput1

C#

using System;
 
public class GFG{
     static int bitCount (int n) {
          n = n - ((n >> 1) & 0x55555555);
          n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
          return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        }
      
     
static void isBitSet(int N)
{
    if (N == Math.Pow(2, bitCount(N)) - 1)
        Console.Write("Yes\n");
    else Console.Write("No\n");
}
 
public static void Main(String[] args)
{
    int N = 7;
    isBitSet(N);
}
}
 
// This code is contributed by umadevi9616

Javascript

<script>
   function bitCount (n) {
        n = n - ((n >> 1) & 0x55555555);
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
        return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
      }
    function isBitSet(N) {
        if (N == Math.pow(2, bitCount(N)) - 1)
            document.write("Yes\n");
        else
            document.write("No\n");
    }
 
        var N = 7;
        isBitSet(N);
 
// This code is contributed by umadevi9616
</script>

Producción:

Yes

Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)

Referencias:  
https://www.careercup.com/question?id=9503107
Este artículo es una contribución de Ayush Jauhari . 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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *