Algorithm/Codility
[Codility] Lesson 1. Iterations - BinaryGap
sirius
2020. 2. 19. 21:44
2진수의 1과 1사이의 간격 중 가장 큰 값을 찾는 문제
public static int solution(int N) {
String str = Integer.toBinaryString(N);
String[] arr = str.split("");
int totalGapLength = 0;
int gapLength = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals("1")) {
if (gapLength > totalGapLength) {
totalGapLength = gapLength;
}
gapLength = 0;
} else if(arr[i].equals("0")) {
gapLength++;
}
}
return totalGapLength;
}