Interview Question
Software EngineersCountry: United States
Interview Type: Phone Interview
We do following
public static int BinaryGap(int n)
{
int maxGap = 0;
int currentGap = 0;
while(n > 0)
{
if(n % 2 == 0)
{
currentGap++;
if(maxGap < currentGap)
{
maxGap = currentGap;
}
}
else if(n % 2 == 1)
{
currentGap = 0;
}
n = n/2;
}
return maxGap;
}
public int solution(int N) {
String binary = Integer.toBinaryString(N);
int compte = 0, comptegap = 0, result = 0;
char[] value = binary.toCharArray();
System.out.println(value);
for (char v : value) {
if (v == '1') {
compte++;
}
if (v == '0') {
if (compte == 2) {
if (result < comptegap) {
result = comptegap;
}
comptegap = 0;
} else {
result = 0;
}
comptegap++;
}
}
return result;
}
- abab April 16, 2020