BinaryGap
Find longest sequence of zeros in binary representation of an integer.
Task Score
93%
Correctness
93%
Performance
Not assessed
업로드 하기는 programmers의 문제들을 먼저 업로드 했지만, 사실은 이 문제가 제일 처음 푼 문제다.
1이 있는 위치를 저장해주고, 그 거리를 계산해서 제일 큰 gap을 리턴한다. result가 -1이 나오는 경우에는 gap이 없는 것이므로 0을 반환하도록 처리해주면 된다.
xxxxxxxxxx
// 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) {
String input = Integer.toBinaryString(N);
int[] arr = new int[input.length()];
int pos = 0;
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == '1') arr[pos++] = i;
}
int result = arr[1] - arr[0] - 1;
for (int i = 2; i < arr.length; i++) {
if (result < arr[i] - arr[i-1] - 1) result = arr[i] - arr[i-1] - 1;
}
if (result < 0) result = 0;
return result;
}
}
'공부 > algorithm' 카테고리의 다른 글
[codility] OddOccurrencesInArray (0) | 2018.05.22 |
---|---|
[codility] CyclicRotation (0) | 2018.05.22 |
[programmers] 숫자의 표현 (0) | 2018.05.22 |
[programmers] 멀리 뛰기 (0) | 2018.05.22 |
[programmers] N개의 최소공배수 (0) | 2018.05.22 |
댓글