Length of longest consecutive zeroes in the binary representation of a number.
Last Updated :
23 Nov, 2022
We have a number N. Determine the length of the longest consecutive 0’s in its binary representation.
Examples:
Input : N = 14
Output : 1
Binary representation of 14 is
1110. There is only one 0 in
the binary representation.
Input : N = 9
Output : 2
A simple approach is to traverse through all bits and keep track of the maximum number of consecutive 0s.
C++
#include <bits/stdc++.h>
using namespace std;
int maxZeros( int N)
{
int maxm = -1;
int cnt = 0;
while (N) {
if (!(N & 1)) {
cnt++;
N >>= 1;
maxm = max(maxm, cnt);
}
else {
maxm = max(maxm, cnt);
cnt = 0;
N >>= 1;
}
}
return maxm;
}
int main()
{
int N = 14;
cout << maxZeros(N) << endl;
return 0;
}
|
Java
public class GFG {
static int maxZeros( int N)
{
int maxm = - 1 ;
int cnt = 0 ;
while (N != 0 ) {
if ((N & 1 ) == 0 ) {
cnt++;
N >>= 1 ;
maxm = Math.max(maxm, cnt);
}
else {
maxm = Math.max(maxm, cnt);
cnt = 0 ;
N >>= 1 ;
}
}
return maxm;
}
public static void main(String args[])
{
int N = 14 ;
System.out.println(maxZeros(N));
}
}
|
Python3
def maxZeros(N):
maxm = - 1
cnt = 0
while (N):
if ( not (N & 1 )):
cnt + = 1
N >> = 1
maxm = max (maxm,cnt)
else :
maxm = max (maxm,cnt)
cnt = 0
N >> = 1
return maxm
N = 14
print (maxZeros(N))
|
C#
using System;
class GFG
{
static int maxZeros( int N)
{
int maxm = -1;
int cnt = 0;
while (N != 0)
{
if ((N & 1) == 0 )
{
cnt++;
N >>= 1;
maxm = Math.Max(maxm, cnt);
}
else
{
maxm = Math.Max(maxm, cnt);
cnt = 0;
N >>= 1;
}
}
return maxm;
}
public static void Main()
{
int N = 14;
Console.WriteLine(maxZeros(N));
}
}
|
PHP
<?php
function maxZeros( $N )
{
$maxm = -1;
$cnt = 0;
while ( $N )
{
if (!( $N & 1))
{
$cnt ++;
$N >>= 1;
$maxm = max( $maxm , $cnt );
}
else
{
$maxm = max( $maxm , $cnt );
$cnt = 0;
$N >>= 1;
}
}
return $maxm ;
}
$N = 14;
echo (maxZeros( $N ));
?>
|
Javascript
<script>
function maxZeros(N)
{
let maxm = -1;
let cnt = 0;
while (N != 0)
{
if ((N & 1) == 0 )
{
cnt++;
N >>= 1;
maxm = Math.max(maxm, cnt);
}
else
{
maxm = Math.max(maxm, cnt);
cnt = 0;
N >>= 1;
}
}
return maxm;
}
let N = 14;
document.write(maxZeros(N));
</script>
|
Time Complexity: O(log2N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...