Highest power of 2 that divides a number represented in binary
Given binary string str, the task is to find the largest power of 2 that divides the decimal equivalent of the given binary number.
Examples:
Input: str = “100100”
Output: 2
22 = 4 is the highest power of 2 that divides 36 (100100).
Input: str = “10010”
Output: 1
Approach: Starting from the right, count the number of 0s in the binary representation which is the highest power of 2 which will divide the number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int highestPower(string str, int len)
{
int ans = 0;
for ( int i = len - 1; i >= 0; i--) {
if (str[i] == '0' )
ans++;
else
break ;
}
return ans;
}
int main()
{
string str = "100100" ;
int len = str.length();
cout << highestPower(str, len);
return 0;
}
|
Java
class GFG
{
static int highestPower(String str, int len)
{
int ans = 0 ;
for ( int i = len - 1 ; i >= 0 ; i--)
{
if (str.charAt(i) == '0' )
ans++;
else
break ;
}
return ans;
}
public static void main(String[] args)
{
String str = "100100" ;
int len = str.length();
System.out.println(highestPower(str, len));
}
}
|
Python3
def highestPower( str , length):
ans = 0 ;
for i in range (length - 1 , - 1 , - 1 ):
if ( str [i] = = '0' ):
ans + = 1 ;
else :
break ;
return ans;
def main():
str = "100100" ;
length = len ( str );
print (highestPower( str , length));
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG
{
static int highestPower(String str, int len)
{
int ans = 0;
for ( int i = len - 1; i >= 0; i--)
{
if (str[i] == '0' )
ans++;
else
break ;
}
return ans;
}
public static void Main(String[] args)
{
String str = "100100" ;
int len = str.Length;
Console.WriteLine(highestPower(str, len));
}
}
|
PHP
<?php
function highestPower( $str , $len )
{
$ans = 0;
for ( $i = $len - 1; $i >= 0; $i --)
{
if ( $str [ $i ] == '0' )
$ans ++;
else
break ;
}
return $ans ;
}
$str = "100100" ;
$len = strlen ( $str );
echo highestPower( $str , $len );
?>
|
Javascript
<script>
function highestPower(str, len)
{
let ans = 0;
for (let i = len - 1; i >= 0; i--) {
if (str[i] == '0' )
ans++;
else
break ;
}
return ans;
}
let str = "100100" ;
let len = str.length;
document.write(highestPower(str, len));
</script>
|
Time Complexity: O(n) where n is number of elements in given array. As, we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(1), as we are not using any extra space.
Last Updated :
28 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...