이진수로 변환한 숫자에서 가장 긴 연속된 0의 길이를 구하는 문제이다.
start
와 end
변수를 통해 양쪽 끝에 있는 1의 위치를 담고 있는 변수이다.start
, end
를 -1로 초기화하고, start
가 -1이라면 제일 처음 만나는 1이기 때문에, 이 인덱스 값을 start
의 값으로 바꿔준다.end
의 값으로 바꿔주고 사이에 있는 0의 개수를 계산한다. 계산이 끝난 후에는 end
값을 start
값으로 바꿔준다.// you can also use imports, for example:
import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int N) {
// write your code in Java SE 8
String binaryString = Integer.toBinaryString(N);
int count = 0;
int start = -1, end = -1;
for(int i=0; i<binaryString.length(); i++){
if(binaryString.charAt(i) == '1'){
if(start == -1){
start = i;
}else{
end = i;
count = Math.max(count, end-start-1);
start = i;
}
}
}
return count;
}
}
Integer.toBinaryString(n)