Given a HUGE number check if it’s a power of two.
Find if a given number, num is the power of 2 or not. More specifically, find if the given number can be expressed as 2^k where k >= 1. Return 1 if the number is a power of 2 else return 0
NOTE :
- A number of digits of the given number i.e (num) can be greater than 100.
- There are no leading zeros before a non-zero number. E.g 0000128 is not in input./li>
Examples:
Input : 3
Output : 0
Explanation: 2^0 = 1 where as k >= 1
Input : 128
Output : 1
Method 1: Using strings
The idea is to repeatedly divide the large number (represented as a string) by 2. To perform division, we traverse digits from right to left. If the last digit itself is not divisible by 2, we return 0. Otherwise, we follow the school method of division.
C
#include <stdio.h>
#include <string.h>
int isPowerOf2( char * str)
{
int len_str = strlen (str);
int num = 0;
if (len_str == 1 && str[len_str - 1] == '1' )
return 0;
while (len_str != 1 || str[len_str - 1] != '1' ) {
if ((str[len_str - 1] - '0' ) % 2 == 1)
return 0;
int j = 0;
for ( int i = 0; i < len_str; i++) {
num = num * 10 + str[i] - '0' ;
if (num < 2) {
if (i != 0)
str[j++] = '0' ;
continue ;
}
str[j++] = ( int )(num / 2) + '0' ;
num = (num) - (num / 2) * 2;
}
str[j] = '\0' ;
len_str = j;
}
return 1;
}
int main()
{
char str1[] = "12468462246684202468024"
"6842024662202000002" ;
char str2[] = "1" ;
char str3[] = "128" ;
printf ( "%d\n%d\n%d" , isPowerOf2(str1),
isPowerOf2(str2), isPowerOf2(str3));
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
int isPowerOf2(string str)
{
int len_str = str.size();
int num = 0;
if (len_str == 1 && str[len_str - 1] == '1' )
return 0;
while (len_str != 1 || str[len_str - 1] != '1' ) {
if ((str[len_str - 1] - '0' ) % 2 == 1)
return 0;
int j = 0;
for ( int i = 0; i < len_str; i++) {
num = num * 10 + str[i] - '0' ;
if (num < 2) {
if (i != 0)
str[j++] = '0' ;
continue ;
}
str[j++] = ( int )(num / 2) + '0' ;
num = (num) - (num / 2) * 2;
}
len_str = j;
}
return 1;
}
int main()
{
string str1 = "12468462246684202468024"
"6842024662202000002" ;
string str2 = "1" ;
string str3 = "128" ;
cout << isPowerOf2(str1) << endl
<< isPowerOf2(str2) << endl
<< isPowerOf2(str3);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int isPowerOf2(String s)
{
char []str = s.toCharArray();
int len_str = s.length();
int num = 0 ;
if (len_str == 1 && str[len_str - 1 ] == '1' )
return 0 ;
while (len_str != 1 || str[len_str - 1 ] != '1' )
{
if ((str[len_str - 1 ] - '0' ) % 2 == 1 )
return 0 ;
int j = 0 ;
for ( int i = 0 ; i < len_str; i++)
{
num = num * 10 + ( int )str[i] - ( int ) '0' ;
if (num < 2 )
{
if (i != 0 )
str[j++] = '0' ;
continue ;
}
str[j++] = ( char )(( int )(num / 2 ) + ( int ) '0' );
num = (num) - (num / 2 ) * 2 ;
}
str[j] = '\0' ;
len_str = j;
}
return 1 ;
}
public static void main (String[] args)
{
String str1 = "124684622466842024680246842024662202000002" ;
String str2 = "1" ;
String str3 = "128" ;
System.out.println(isPowerOf2(str1) +
"\n" +isPowerOf2(str2) +
"\n" +isPowerOf2(str3));
}
}
|
Python3
def isPowerOf2(sttr):
len_str = len (sttr);
sttr = list (sttr);
num = 0 ;
if (len_str = = 1 and sttr[len_str - 1 ] = = '1' ):
return 0 ;
while (len_str ! = 1 or sttr[len_str - 1 ] ! = '1' ):
if (( ord (sttr[len_str - 1 ]) - ord ( '0' )) % 2 = = 1 ):
return 0 ;
j = 0 ;
for i in range (len_str):
num = num * 10 + ( ord (sttr[i]) - ord ( '0' ));
if (num < 2 ):
if (i ! = 0 ):
sttr[j] = '0' ;
j + = 1 ;
continue ;
sttr[j] = chr ((num / / 2 ) + ord ( '0' ));
j + = 1 ;
num = (num) - (num / / 2 ) * 2 ;
len_str = j;
return 1 ;
str1 = "124684622466842024680246842024662202000002" ;
str2 = "1" ;
str3 = "128" ;
print (" ", isPowerOf2(str1), " \n",
isPowerOf2(str2), "\n" ,
isPowerOf2(str3));
|
C#
using System;
class GFG
{
static int isPowerOf2( string s)
{
char []str = s.ToCharArray();
int len_str = str.Length;
int num = 0;
if (len_str == 1 && str[len_str - 1] == '1' )
return 0;
while (len_str != 1 || str[len_str - 1] != '1' )
{
if ((str[len_str - 1] - '0' ) % 2 == 1)
return 0;
int j = 0;
for ( int i = 0; i < len_str; i++)
{
num = num * 10 + ( int )str[i] - ( int ) '0' ;
if (num < 2)
{
if (i != 0)
str[j++] = '0' ;
continue ;
}
str[j++] = ( char )(( int )(num / 2) + ( int ) '0' );
num = (num) - (num / 2) * 2;
}
str[j] = '\0' ;
len_str = j;
}
return 1;
}
static void Main()
{
string str1 = "124684622466842024680246842024662202000002" ;
string str2 = "1" ;
string str3 = "128" ;
Console.Write(isPowerOf2(str1) +
"\n" +isPowerOf2(str2) +
"\n" +isPowerOf2(str3));
}
}
|
PHP
<?php
function isPowerOf2( $str )
{
$len_str = strlen ( $str );
$num = 0;
if ( $len_str == 1 && $str [ $len_str - 1] == '1' )
return 0;
while ( $len_str != 1 || $str [ $len_str - 1] != '1' )
{
if (ord( $str [ $len_str - 1] - '0' ) % 2 == 1)
return 0;
$j =0;
for ( $i = 0; $i < $len_str ; $i ++)
{
$num = $num * 10 + (ord( $str [ $i ]) - ord( '0' ));
if ( $num < 2)
{
if ( $i != 0)
$str [ $j ++] = '0' ;
continue ;
}
$str [ $j ++] = chr ((int)( $num / 2) + ord( '0' ));
$num = ( $num ) - (int)( $num / 2) * 2;
}
$len_str = $j ;
}
return 1;
}
$str1 = "124684622466842024680246842024662202000002" ;
$str2 = "1" ;
$str3 = "128" ;
print (isPowerOf2( $str1 ). "\n" .isPowerOf2( $str2 ). "\n" .isPowerOf2( $str3 ));
?>
?>
|
Javascript
function isPowerOf2(str)
{
let len_str = str.length;
let num = 0;
if (len_str == 1 && str.charAt(len_str - 1) == '1' )
return 0;
while (len_str != 1 || str.charAt(len_str - 1) != '1' ) {
if ( parseInt(str.charAt(len_str - 1)) % 2 == 1)
return 0;
let j = 0;
for (let i = 0; i < len_str; i++) {
num = num * 10 + parseInt(str.charAt(i));
if (num < 2) {
if (i != 0)
{
str = str.substring(0, j) + '0' + str.substring(j + 1);
j++;
}
continue ;
}
str = str.substring(0, j) + (Math.floor(num / 2)).toString() + str.substring(j + 1);
j++;
num = (num) - Math.floor(num / 2) * 2;
}
len_str = j;
}
return 1;
}
let str1 = "124684622466842024680246842024662202000002" ;
let str2 = "1" ;
let str3 = "128" ;
console.log(isPowerOf2(str1));
console.log(isPowerOf2(str2));
console.log(isPowerOf2(str3));
|
Time Complexity: O(N^2) where N is a number of digits in the given number.
Method 2: Using boost library
Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications. For example, they are helpful for handling large numbers having a range beyond the long long, long double data type (264) in C++.
- Take input as a boost integer.
- Using bit manipulation check whether it’s the power of 2 or not.
C++
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using namespace boost::multiprecision;
bool ispowerof2 ( cpp_int num )
{
if ( ( num & ( num - 1 ) ) == 0 )
return 1;
return 0;
}
int main()
{
cpp_int num = 549755813888;
cout << ispowerof2 ( num ) << endl;
return 0;
}
|
Java
class GfG
{
static long ispowerof2 ( long num )
{
if ((num & (num - 1 )) == 0 )
return 1 ;
return 0 ;
}
public static void main(String[] args)
{
long num = 549755813888L;
System.out.println(ispowerof2(num));
}
}
|
Python3
def ispowerof2(num):
if ((num & (num - 1 )) = = 0 ):
return 1
return 0
if __name__ = = '__main__' :
num = 549755813888
print (ispowerof2(num))
|
C#
class GFG{
static long ispowerof2 ( long num )
{
if ((num&(num-1)) == 0)
return 1;
return 0;
}
public static void Main()
{
long num = 549755813888;
System.Console.WriteLine(ispowerof2(num));
}
}
|
PHP
<?php
function ispowerof2 ( $num )
{
if (( $num & ( $num - 1 )) == 0)
return 1;
return 0;
}
$num = 549755813888;
echo ispowerof2( $num );
?>
|
Javascript
<script>
function ispowerof2(num)
{
if ((num & (num - 1)) == 0)
return 1;
return 0;
}
var num = 549755813888;
document.write(ispowerof2(num));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 3: Using logical and bitwise operators
If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit becomes unset.
So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on the value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1))
C++
#include <iostream>
using namespace std;
int main()
{
long int x = 128;
if (x and (not(x & (x - 1)))){
cout<< "Yes" ;
}
else
{
cout<< "No" ;
}
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
int x = 128 ;
if ((x != 0 ) && ( 0 == (x & (x - 1 )))) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
}
|
Python3
x = 128
if (x and ( not (x & (x - 1 )))):
print ( "yes" )
else :
print ( "no" )
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static void Main( string [] args)
{
int x = 128;
if ((x != 0) && (0 == (x & (x - 1)))) {
Console.Write( "Yes" );
}
else {
Console.Write( "No" );
}
}
}
|
Javascript
<script>
var x = 128;
if (x and (not(x & (x - 1))))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 4: Using log() function
The idea is to find Log n in base 2 and store it in integer as well as double variables, if the integer value is the same as the double value then the result is true, else the result is false.
C++
#include <iostream>
#include <math.h>
using namespace std;
bool isPowerOfTwo( int y)
{
int res1 = log (y) / log (2);
double res2 = log (y) / log (2);
return (res1 == res2);
}
int main()
{
cout << isPowerOfTwo(128) << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static boolean isPowerOfTwo( int y)
{
int res1 = ( int )(Math.log(y) / Math.log( 2 ));
double res2 = Math.log(y) / Math.log( 2 );
return (res1 == res2);
}
public static void main(String[] args)
{
if (isPowerOfTwo( 128 ))
System.out.println( 1 );
else
System.out.println( 0 );
}
}
|
Python3
import math
def isPowerOfTwo(y):
res1 = int (math.log(y) / / math.log( 2 ))
res2 = math.log(y) / / math.log( 2 )
return res1 = = res2
if (isPowerOfTwo( 128 )):
print ( 1 )
else :
print ( 0 )
|
C#
using System;
public class GFG {
static bool isPowerOfTwo( int y)
{
int res1 = ( int )(Math.Log(y) / Math.Log(2));
double res2 = Math.Log(y) / Math.Log(2);
return (res1 == res2);
}
static public void Main()
{
if (isPowerOfTwo(128))
Console.WriteLine(1);
else
Console.WriteLine(0);
}
}
|
Javascript
function isPowerOfTwo( y)
{
let res1 = Math.log2(y);
res1= Math.round(res1);
let res2 = Math.log2(y);
return (res1 == res2);
}
if (isPowerOfTwo(128)== true )
console.log(1);
else
console.log(0);
|
Time Complexity: O(log(log(N))), for using the inbuilt log() function.
Auxiliary Space: O(1)
Reference: https://www.boost.org/doc/libs/1_61_0/libs/multiprecision/doc/html/index.html
Last Updated :
08 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...