Codility Task:
BinaryGap
Problem Definition:
Find the longest sequence of zeros in binary representation of an integer.
Solution:
This file contains hidden or 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 int solution(int N) { | |
String binary = Integer.toBinaryString(N); | |
int i = binary.length() - 1; | |
while(binary.charAt(i) == '0') { | |
i--; | |
} | |
int binaryGap = 0; | |
int tempBinaryGap = 0; | |
for(; i >= 0; i--) { | |
if (binary.charAt(i) == '1') { | |
binaryGap = Math.max(binaryGap, tempBinaryGap); | |
tempBinaryGap = 0; | |
} else { | |
tempBinaryGap++; | |
} | |
} | |
return binaryGap; | |
} |
0 comments:
Post a Comment