Programa para encontrar si un número dado es potencia de 2 – Part 1

Dado un entero positivo, escribe una función para encontrar si es una potencia de dos o no.
Ejemplos: 

Input : n = 4
Output : Yes
22 = 4

Input : n = 7
Output : No

Input : n = 32
Output : Yes
25 = 32

1. Un método simple para esto es simplemente tomar el logaritmo del número en base 2 y si obtienes un número entero, entonces el número es la potencia de 2.

C++

// C++ Program to find whether a
// no is power of two
#include<bits/stdc++.h>
using namespace std;
 
// Function to check if x is power of 2
bool isPowerOfTwo(int n)
{
   if(n==0)
   return false;
 
   return (ceil(log2(n)) == floor(log2(n)));
}
 
// Driver program
int main()
{
    isPowerOfTwo(31)? cout<<"Yes"<<endl: cout<<"No"<<endl;
    isPowerOfTwo(64)? cout<<"Yes"<<endl: cout<<"No"<<endl;
 
    return 0;
}
 
// This code is contributed by Surendra_Gangwar

C

// C Program to find whether a
// no is power of two
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
 
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
   if(n==0)
   return false;
 
   return (ceil(log2(n)) == floor(log2(n)));
}
 
// Driver program
int main()
{
    isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
    isPowerOfTwo(64)? printf("Yes\n"): printf("No\n");
    return 0;
}
 
// This code is contributed by bibhudhendra

Java

// Java Program to find whether a
// no is power of two
class GFG
{
/* Function to check if x is power of 2*/
static boolean isPowerOfTwo(int n)
{
    if(n==0)
    return false;
 
return (int)(Math.ceil((Math.log(n) / Math.log(2)))) ==
       (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
 
// Driver Code
public static void main(String[] args)
{
    if(isPowerOfTwo(31))
    System.out.println("Yes");
    else
    System.out.println("No");
     
    if(isPowerOfTwo(64))
    System.out.println("Yes");
    else
    System.out.println("No");
}
}
 
// This code is contributed by mits

Python3

# Python3 Program to find
# whether a no is
# power of two
import math
 
# Function to check
# Log base 2
def Log2(x):
    if x == 0:
        return false;
 
    return (math.log10(x) /
            math.log10(2));
 
# Function to check
# if x is power of 2
def isPowerOfTwo(n):
    return (math.ceil(Log2(n)) ==
            math.floor(Log2(n)));
 
# Driver Code
if(isPowerOfTwo(31)):
    print("Yes");
else:
    print("No");
 
if(isPowerOfTwo(64)):
    print("Yes");
else:
    print("No");
     
# This code is contributed
# by mits

C#

// C# Program to find whether
// a no is power of two
using System;
 
class GFG
{
     
/* Function to check if
   x is power of 2*/
static bool isPowerOfTwo(int n)
{
 
    if(n==0)
     return false;
 
    return (int)(Math.Ceiling((Math.Log(n) /
                               Math.Log(2)))) ==
           (int)(Math.Floor(((Math.Log(n) /
                              Math.Log(2)))));
}
 
// Driver Code
public static void Main()
{
    if(isPowerOfTwo(31))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
     
    if(isPowerOfTwo(64))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

PHP

<?php
// PHP Program to find
// whether a no is
// power of two
 
// Function to check
// Log base 2
function Log2($x)
{
    return (log10($x) /
            log10(2));
}
 
 
// Function to check
// if x is power of 2
function isPowerOfTwo($n)
{
    return (ceil(Log2($n)) ==
            floor(Log2($n)));
}
 
// Driver Code
if(isPowerOfTwo(31))
echo "Yes\n";
else
echo "No\n";
 
if(isPowerOfTwo(64))
echo "Yes\n";
else
echo "No\n";
     
// This code is contributed
// by Sam007
?>

Javascript

<script>
// javascript Program to find whether a
// no is power of two
 
    /* Function to check if x is power of 2 */
    function isPowerOfTwo(n)
    {
        if (n == 0)
            return false;
 
        return parseInt( (Math.ceil((Math.log(n) / Math.log(2))))) == parseInt( (Math.floor(((Math.log(n) / Math.log(2))))));
    }
 
    // Driver Code
     
    if (isPowerOfTwo(31))
        document.write("Yes<br/>");
    else
        document.write("No<br/>");
 
    if (isPowerOfTwo(64))
        document.write("Yes<br/>");
    else
        document.write("No<br/>");
 
// This code is contributed by shikhasingrajput.
</script>

Producción:  

No
Yes

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

2. Otra solución es seguir dividiendo el número por dos, es decir, hacer n = n/2 iterativamente. En cualquier iteración, si n%2 se vuelve distinto de cero y n no es 1, entonces n no es una potencia de 2. Si n se convierte en 1, entonces es una potencia de 2. 

C++

#include <bits/stdc++.h>
using namespace std;
 
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
    if (n == 0)
        return 0;
    while (n != 1)
    {
        if (n%2 != 0)
            return 0;
        n = n/2;
    }
    return 1;
}
 
/*Driver code*/
int main()
{
    isPowerOfTwo(31)? cout<<"Yes\n": cout<<"No\n";
    isPowerOfTwo(64)? cout<<"Yes\n": cout<<"No\n";
    return 0;
}
 
// This code is contributed by rathbhupendra

C

#include<stdio.h>
#include<stdbool.h>
 
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
  if (n == 0)
    return 0;
  while (n != 1)
  {
      if (n%2 != 0)
         return 0;
      n = n/2;
  }
  return 1;
}
 
/*Driver program to test above function*/
int main()
{
  isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(64)? printf("Yes\n"): printf("No\n");
  return 0;
}

Java

// Java program to find whether
// a no is power of two
import java.io.*;
 
class GFG {
 
    // Function to check if
    // x is power of 2
    static boolean isPowerOfTwo(int n)
    {
        if (n == 0)
            return false;
         
        while (n != 1)
        {
            if (n % 2 != 0)
                return false;
            n = n / 2;
        }
        return true;
    }
 
    // Driver program
    public static void main(String args[])
    {
        if (isPowerOfTwo(31))
            System.out.println("Yes");
        else
            System.out.println("No");
 
        if (isPowerOfTwo(64))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Nikita tiwari.

Python3

# Python program to check if given
# number is power of 2 or not
 
# Function to check if x is power of 2
def isPowerOfTwo(n):
    if (n == 0):
        return False
    while (n != 1):
            if (n % 2 != 0):
                return False
            n = n // 2
             
    return True
 
# Driver code
if(isPowerOfTwo(31)):
    print('Yes')
else:
    print('No')
if(isPowerOfTwo(64)):
    print('Yes')
else:
    print('No')
 
# This code is contributed by Danish Raza

C#

// C# program to find whether
// a no is power of two
using System;
 
class GFG
{
     
    // Function to check if
    // x is power of 2
    static bool isPowerOfTwo(int n)
    {
        if (n == 0)
            return false;
         
        while (n != 1) {
            if (n % 2 != 0)
                return false;
                 
            n = n / 2;
        }
        return true;
    }
 
    // Driver program
    public static void Main()
    {
        Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
        Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
 
    }
}
 
// This code is contributed by Sam007

PHP

<?php
 
// Function to check if
// x is power of 2
function isPowerOfTwo($n)
{
if ($n == 0)
    return 0;
while ($n != 1)
{
    if ($n % 2 != 0)
        return 0;
    $n = $n / 2;
}
return 1;
}
 
// Driver Code
if(isPowerOfTwo(31))
    echo "Yes\n";
else
    echo "No\n";
 
if(isPowerOfTwo(64))
    echo "Yes\n";
else
    echo "No\n";
 
// This code is contributed
// by Sam007
?>

Javascript

<script>
 
    /* Function to check if x is power of 2*/
    function isPowerOfTwo(n)
    {
        if (n == 0)
            return 0;
        while (n != 1)
        {
            if (n%2 != 0)
                return 0;
            n = n/2;
        }
        return 1;
    } 
     
    isPowerOfTwo(31)? document.write("Yes" + "</br>"): document.write("No" + "</br>");
    isPowerOfTwo(64)? document.write("Yes"): document.write("No");
 
</script>

Producción :  

No
Yes

Complejidad del tiempo: O(log 2 n)

Espacio Auxiliar: O(1)

3. Otra forma es usar esta solución recursiva simple. Utiliza la misma lógica que la solución iterativa anterior, pero utiliza la recursividad en lugar de la iteración. 

C++

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function which checks whether a number is a power of 2
bool powerOf2(int n)
{
    // base cases
    // '1' is the only odd number which is a power of 2(2^0)
    if (n == 1)
        return true;
 
    // all other odd numbers are not powers of 2
    else if (n % 2 != 0 || n == 0)
        return false;
 
    // recursive function call
    return powerOf2(n / 2);
}
 
// Driver Code
int main()
{
    int n = 64; // True
    int m = 12; // False
 
    if (powerOf2(n) == 1)
        cout << "True" << endl;
 
    else
        cout << "False" << endl;
 
    if (powerOf2(m) == 1)
        cout << "True" << endl;
 
    else
        cout << "False" << endl;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C

// C program for above approach
#include <stdbool.h>
#include <stdio.h>
 
// Function which checks whether a number is a power of 2
bool powerOf2(int n)
{
    // base cases
    // '1' is the only odd number which is a power of 2(2^0)
    if (n == 1)
        return true;
 
    // all other odd numbers are not powers of 2
    else if (n % 2 != 0 || n == 0)
        return false;
 
    // recursive function call
    return powerOf2(n / 2);
}
 
// Driver Code
int main()
{
    int n = 64; // True
    int m = 12; // False
 
    if (powerOf2(n) == 1)
        printf("True\n");
 
    else
        printf("False\n");
 
    if (powerOf2(m) == 1)
        printf("True\n");
 
    else
        printf("False\n");
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function which checks
// whether a number is a
// power of 2
static boolean powerOf2(int n)
{
  // base cases
  // '1' is the only odd number
  // which is a power of 2(2^0)
  if (n == 1)
    return true;
 
  // all other odd numbers are
  // not powers of 2
  else if (n % 2 != 0 ||
           n ==0)
    return false;
 
  // recursive function call
  return powerOf2(n / 2);
}
 
// Driver Code
public static void main(String[] args)
{
  //True
  int n = 64;
   
  //False
  int m = 12;
 
  if (powerOf2(n) == true)
    System.out.print("True" + "\n");
  else System.out.print("False" + "\n");
 
  if (powerOf2(m) == true)
    System.out.print("True" + "\n");
  else
    System.out.print("False" + "\n");
}
}
 
// This code is contributed by Princi Singh

Python3

# Python program for above approach
 
# function which checks whether a
# number is a power of 2
def powerof2(n):
   
    # base cases
    # '1' is the only odd number
    # which is a power of 2(2^0)
    if n == 1:
        return True
     
    # all other odd numbers are not powers of 2
    elif n%2 != 0 or n == 0:
        return False
     
    #recursive function call
    return powerof2(n/2)
   
# Driver Code
if __name__ == "__main__":
   
  print(powerof2(64)) #True
  print(powerof2(12)) #False
   
#code contributed by Moukthik a.k.a rowdyninja

C#

// C# program for above approach
using System;
 
class GFG{
     
// Function which checks whether a
// number is a power of 2
static bool powerOf2(int n)
{
     
    // Base cases
    // '1' is the only odd number
    // which is a power of 2(2^0)
    if (n == 1)
      return true;
      
    // All other odd numbers
    // are not powers of 2
    else if (n % 2 != 0 || n == 0)
      return false;
      
    // Recursive function call
    return powerOf2(n / 2);
}
 
// Driver code
static void Main()
{
   
    int n = 64;//True
    int m = 12;//False
     
    if (powerOf2(n))
    {
        Console.Write("True" + "\n");
    }
    else
    {
        Console.Write("False" + "\n");
    }
     
    if (powerOf2(m))
    {
        Console.Write("True");
    }
    else
    {
        Console.Write("False");
    }
}
}
 
// This code is contributed by rutvik_56

Javascript

<script>
 
// javascript program for
// the above approach
 
// Function which checks
// whether a number is a
// power of 2
 
function powerOf2(n)
{
  // base cases
  // '1' is the only odd number
  // which is a power of 2(2^0)
  if (n == 1)
    return true;
 
  // all other odd numbers are
  // not powers of 2
  else if (n % 2 != 0 ||
           n ==0)
    return false;
 
  // recursive function call
  return powerOf2(n / 2);
}
 
// Driver Code
//True
var n = 64;
 
//False
var m = 12;
 
if (powerOf2(n) == true)
  document.write("True" + "\n");
else document.write("False" + "\n");
 
if (powerOf2(m) == true)
  document.write("True" + "\n");
else
  document.write("False" + "\n");
   
// This code contributed by shikhasingrajput
 
</script>
Producción

True
False

Complejidad del tiempo: O(log 2 n)

Espacio Auxiliar: O(log 2 n)

4. Toda potencia de dos números tiene solo un conjunto de un bit. Así que cuenta el no. de bits establecidos y si obtiene 1, entonces el número es una potencia de 2. Consulte Contar bits establecidos en un número entero para contar bits establecidos.

C++

#include <bits/stdc++.h>
using namespace std;
#define bool int
 
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
    /* First x in the below expression is for the case when
     * x is 0 */
    int cnt = 0;
    while (n > 0) {
        if ((n & 1) == 1) {
            cnt++;
        }
        n = n >> 1;// keep dividing n by 2 using right
                        // shift operator
    }
 
    if (cnt == 1) {// if cnt = 1 only then it is power of 2
        return true;
    }
    return false;
}
 
/*Driver code*/
int main()
{
    isPowerOfTwo(31) ? cout << "Yes\n" : cout << "No\n";
    isPowerOfTwo(64) ? cout << "Yes\n" : cout << "No\n";
    return 0;
}
 
// This code is contributed by devendra salunke

Java

// Java program of the above approach
import java.io.*;
 
class GFG {
 
    // Function to check if x is power of 2
    static boolean isPowerofTwo(int n)
    {
        int cnt = 0;
        while (n > 0) {
            if ((n & 1) == 1) {
                cnt++; // if n&1 == 1 keep incrementing cnt
                // variable
            }
            n = n >> 1; // keep dividing n by 2 using right
                        // shift operator
        }
        if (cnt == 1) {
            // if cnt = 1 only then it is power of 2
            return true;
        }
        return false;
    }
    public static void main(String[] args)
    {
        if (isPowerofTwo(30) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
 
        if (isPowerofTwo(128) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by devendra salunke.

C#

// C# program to check for power for 2
using System;
 
class GFG {
    // Method to check if x is power of 2
    static bool isPowerOfTwo(int n)
    {
        int cnt = 0; // initialize count to 0
        while (n > 0) {
            // run loop till n > 0
            if ((n & 1) == 1) {
                // if n&1 == 1 keep incrementing cnt
                // variable
                cnt++;
            }
            n = n >> 1; // keep dividing n by 2 using right
                        // shift operator
        }
 
        if (cnt == 1) // if cnt = 1 only then it is power of 2
            return true;
        return false;
    }
 
    // Driver method
    public static void Main()
    {
        Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
        Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
    }
}
 
// This code is contributed by devendra salunke

Python3

# Python program to check if given
# number is power of 2 or not
 
# Function to check if x is power of 2
 
 
def isPowerOfTwo(n):
    cnt = 0
    while n > 0:
        if n & 1 == 1:
            cnt = cnt + 1
        n = n >> 1
     
    if cnt == 1 : return 1
    return 0
 
       
# Driver code
if(isPowerOfTwo(31)):
    print('Yes')
else:
    print('No')
 
if(isPowerOfTwo(64)):
    print('Yes')
else:
    print('No')
 
# This code is contributed by devendra salunke

Javascript

<script>
    // JavaScript code for the above approach
 
    // Function to check if x is power of 2
    function isPowerofTwo(n)
    {
        let cnt = 0;
        while (n > 0) {
            if ((n & 1) == 1) {
                cnt++; // if n&1 == 1 keep incrementing cnt
                // variable
            }
            n = n >> 1; // keep dividing n by 2 using right
                        // shift operator
        }
        if (cnt == 1) {
            // if cnt = 1 only then it is power of 2
            return true;
        }
        return false;
    }
 
    // Driver code
 
    if (isPowerofTwo(30) == true)
            document.write("Yes" + "<br/>");
        else
            document.write("No" + "<br/>");
 
        if (isPowerofTwo(128) == true)
            document.write("Yes" + "<br/>");
        else
            document.write("No" + "<br/>");
             
            // This code is contributed by sanjoy_62.
  </script>

Producción : 

No
Yes

Complejidad del tiempo : O(N)

Complejidad espacial : O(1)

5. Si restamos una potencia de 2 números por 1, todos los bits no establecidos después del único bit establecido se establecerán; y el bit establecido se desactiva.
Por ejemplo, para 4 (100) y 16 (10000), obtenemos lo siguiente después de restar 1 
3 –> 011 
15 –> 01111

Entonces, si un número n es una potencia de 2, bit a bit & de n y n-1 será cero. Podemos decir que n es una potencia de 2 o no según el valor de n&(n-1). La expresión n&(n-1) no funcionará cuando n sea 0. Para manejar este caso también, nuestra expresión se convertirá en n& (!n&(n-1)) (gracias a https://www.geeksforgeeks.org/program -para-encontrar-si-un-no-es-poder-de-dos/ Mohammad por agregar este caso). 

A continuación se muestra la implementación de este método.  

Complejidad del tiempo : O(1)

Complejidad del espacio : O(1) 

C++

#include <bits/stdc++.h>
using namespace std;
#define bool int
 
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
    /* First x in the below expression is for the case when x is 0 */
    return x && (!(x&(x-1)));
}
 
/*Driver code*/
int main()
{
    isPowerOfTwo(31)? cout<<"Yes\n": cout<<"No\n";
    isPowerOfTwo(64)? cout<<"Yes\n": cout<<"No\n";
    return 0;
}
 
// This code is contributed by rathbhupendra

C

#include<stdio.h>
#define bool int
 
/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
  /* First x in the below expression is for the case when x is 0 */
  return x && (!(x&(x-1)));
}
 
/*Driver program to test above function*/
int main()
{
  isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(64)? printf("Yes\n"): printf("No\n");
  return 0;
}

Java

// Java program to efficiently
// check for power for 2
 
class Test
{
    /* Method to check if x is power of 2*/
    static boolean isPowerOfTwo (int x)
    {
      /* First x in the below expression is
        for the case when x is 0 */
        return x!=0 && ((x&(x-1)) == 0);
         
    }
     
    // Driver method
    public static void main(String[] args)
    {
         System.out.println(isPowerOfTwo(31) ? "Yes" : "No");
         System.out.println(isPowerOfTwo(64) ? "Yes" : "No");
         
    }
}
// This program is contributed by Gaurav Miglani   

Python3

# Python program to check if given
# number is power of 2 or not
 
# Function to check if x is power of 2
def isPowerOfTwo (x):
 
    # First x in the below expression
    # is for the case when x is 0
    return (x and (not(x & (x - 1))) )
 
# Driver code
if(isPowerOfTwo(31)):
    print('Yes')
else:
    print('No')
     
if(isPowerOfTwo(64)):
    print('Yes')
else:
    print('No')
     
# This code is contributed by Danish Raza   

C#

// C# program to efficiently
// check for power for 2
using System;
 
class GFG
{
    // Method to check if x is power of 2
    static bool isPowerOfTwo (int x)
    {
        // First x in the below expression 
        // is for the case when x is 0
        return x != 0 && ((x & (x - 1)) == 0);
         
    }
     
    // Driver method
    public static void Main()
    {
        Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
        Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
         
    }
}
 
// This code is contributed by Sam007

PHP

<?php
// PHP program to efficiently
// check for power for 2
 
// Function to check if
// x is power of 2
function isPowerOfTwo ($x)
{
// First x in the below expression
// is for the case when x is 0
return $x && (!($x & ($x - 1)));
}
 
// Driver Code
if(isPowerOfTwo(31))
    echo "Yes\n" ;
else
    echo "No\n";
 
if(isPowerOfTwo(64))
    echo "Yes\n" ;
else
    echo "No\n";
         
// This code is contributed by Sam007
?>

Javascript

<script>
 
// JavaScript program to efficiently
// check for power for 2  
 
/* Method to check if x is power of 2*/
    function isPowerOfTwo (x)
    {
      /* First x in the below expression is
        for the case when x is 0 */
        return x!=0 && ((x&(x-1)) == 0);
         
    }
     
// Driver method
document.write(isPowerOfTwo(31) ? "Yes" : "No");
document.write("<br>"+(isPowerOfTwo(64) ? "Yes" : "No"));
 
// This code is contributed by 29AjayKumar
 
</script>

Producción :  

No
Yes

Complejidad de tiempo: O(1)

Espacio Auxiliar: O(1)

6 _ Otra forma es usar la lógica para encontrar el conjunto de bits más a la derecha de un número dado.

C++

#include <iostream>
using namespace std;
 
/* Function to check if x is power of 2*/
bool isPowerofTwo(long long n)
{
    if (n == 0)
        return 0;
    if ((n & (~(n - 1))) == n)
        return 1;
    return 0;
}
/*Driver code*/
int main()
{
 
    isPowerofTwo(30) ? cout << "Yes\n" : cout << "No\n";
    isPowerofTwo(128) ? cout << "Yes\n" : cout << "No\n";
    return 0;
}
// This code is contributed by Sachin

Java

// Java program of the above approach
import java.io.*;
 
class GFG {
   
    // Function to check if x is power of 2
    static boolean isPowerofTwo(int n)
    {
        if (n == 0)
            return false;
        if ((n & (~(n - 1))) == n)
            return true;
        return false;
    }
    public static void main(String[] args)
    {
        if (isPowerofTwo(30) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
       
          if (isPowerofTwo(128) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
                 
    }
}
 
// This code is contributed by rajsanghavi9.

Python3

# Python program of the above approach
 
# Function to check if x is power of 2*/
def isPowerofTwo(n):
 
    if (n == 0):
        return 0
    if ((n & (~(n - 1))) == n):
        return 1
    return 0
 
# Driver code
if(isPowerofTwo(30)):
    print('Yes')
else:
    print('No')
     
if(isPowerofTwo(128)):
    print('Yes')
else:
    print('No')
     
# This code is contributed by shivanisinghss2110

C#

// C# program of the above approach
 
 
using System;
public class GFG {
   
    // Function to check if x is power of 2
    static bool isPowerofTwo(int n)
    {
        if (n == 0)
            return false;
        if ((n & (~(n - 1))) == n)
            return true;
        return false;
    }
    public static void Main(String[] args)
    {
        if (isPowerofTwo(30) == true)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
       
          if (isPowerofTwo(128) == true)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
                 
    }
}
 
// This code contributed by gauravrajput1

Javascript

<script>
// javascript program of the above approach
  
    // Function to check if x is power of 2
    function isPowerofTwo(n)
    {
        if (n == 0)
            return false;
        if ((n & (~(n - 1))) == n)
            return true;
        return false;
    }
 
        if (isPowerofTwo(30) == true)
            document.write("Yes<br/>");
        else
            document.write("No<br/>");
       
          if (isPowerofTwo(128) == true)
            document.write("Yes<br/>");
        else
            document.write("No<br/>");
                 
// This code is contributed by umadevi9616
</script>
Producción

No
Yes

Complejidad del tiempo : O(1)

Complejidad del espacio : O(1) 

7. Algoritmo de Brian Kernighan ( método eficiente )

Acercarse :

Como sabemos que el número que será la potencia de dos tiene solo un bit establecido, por lo tanto, cuando lo hacemos bit a bit y con el número que es justo menor que el número que se puede representar como la potencia de (2), entonces el resultado será ser 0 . 

Ejemplo: 4 se puede representar como (2^2), 

             (4 y 3)=0 o en binario (100 y 011=0)

Aquí está el código del enfoque dado:

C++

// C++ program to check whether the given number is power of
// 2
#include <iostream>
using namespace std;
/* Function to check if x is power of 2*/
bool isPowerofTwo(long long n)
{
    return (n != 0) && ((n & (n - 1)) == 0);
}
/*Driver code*/
int main()
{
    isPowerofTwo(30) ? cout << "Yes\n" : cout << "No\n";
    isPowerofTwo(128) ? cout << "Yes\n" : cout << "No\n";
    return 0;
}
// This code is contributed by Suruchi Kumari

Java

/*package whatever //do not write package name here */
import java.io.*;
class GFG {
 
  /* Function to check if x is power of 2*/
  public static boolean isPowerofTwo(long n)
  {
    return (n != 0) && ((n & (n - 1)) == 0);
  }
  public static void main (String[] args) {
 
    if(isPowerofTwo(30))
    {
      System.out.println("Yes");
    }
    else
    {
      System.out.println("No");
    }
 
    if(isPowerofTwo(128))
    {
      System.out.println("Yes");
    }
    else
    {
      System.out.println("No");
    }
  }
}
 
// This code is contributed by akashish__

Python3

# Python3 program to check whether the given number is power of
# 2
   
# Function to check if x is power of 2
def isPowerofTwo(n) :
     
    return (n != 0) and ((n & (n - 1)) == 0)
     
# Driver code
if __name__ == "__main__" :
     
    if isPowerofTwo(30) :
        print("Yes")
    else :
        print("No")
         
    if isPowerofTwo(128) :
        print("Yes")
    else :
        print("No")
 
# this code is contributed by aditya942003patil

C#

using System;
 
public class GFG{
  /* Function to check if x is power of 2*/
  static public bool isPowerofTwo(ulong n)
{
    return (n != 0) && ((n & (n - 1)) == 0);
}
 
    static public void Main (){
       
      if(isPowerofTwo(30))
      {
        System.Console.WriteLine("Yes");
      }
      else
      {
         System.Console.WriteLine("No");
      }
       
       if(isPowerofTwo(128))
      {
        System.Console.WriteLine("Yes");
      }
      else
      {
         System.Console.WriteLine("No");
      }
       
    }
}
 
// This code is contributed by akashish__

Producción :

No
Yes

Complejidad de tiempo : O(1) 

Espacio Auxiliar: O(1)

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 *