Last active
June 22, 2016 02:03
-
-
Save tiagopereira17/4c71d6402351b3596a3afc91a4632b30 to your computer and use it in GitHub Desktop.
Find the longest sequence of zeros in binary representation of an integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BinaryGap { | |
public int solution(int N) { | |
int max = 0; | |
int counter = 0; | |
boolean isCounting = false; | |
while(N > 0) { | |
if((N & 1) == 1) { | |
if(isCounting) { | |
max = Math.max(max, counter); | |
counter = 0; | |
} else { | |
isCounting = true; | |
counter = 0; | |
} | |
} else { | |
if(isCounting) { | |
counter++; | |
} | |
} | |
N >>= 1; | |
} | |
return max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment