Suppose we have a number n, we have to find the length of the longest consecutive run of 1s in its binary representation.
So, if the input is like n = 312, then the output will be 3, as 312 is 100111000 in binary and there are 3 consecutive 1s.
To solve this, we will follow these steps −
ret := 0, len := 0
for initialize i := 0, when i < 32, update (increase i by 1), do:
if n/2 is odd, then
(increase len by 1)
Otherwise
len := 0
ret := maximum of ret and len
return ret
Let us see the following implementation to get better understanding:
Source Code (C++) −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(int n) {
int ret = 0;
int len = 0;
for(int i = 0; i < 32; i++){
if((n >> i) & 1){
len++;
}else{
len = 0;
}
ret = max(ret, len);
}
return ret;
}
};
main(){
Solution ob;
cout << ob.solve(312);
}Input
312
Output
3