코딜리티에서 첫 코딩 연습을 했다.
백준알고리즘이나 이것저것 찾아봤는데 문제를 보면서 코드를 작성하고, 컴파일링 할 수 있는 곳은 코딜리티가 제일 좋은 것 같았다.
이번 문제는 2진법으로 바꾼 수에서 1과 1사이 0의 개수를 구하는 문제이다.
Task Description
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [1..2,147,483,647].
나의 풀이!
class Solution {
public int solution(int N) {
String binary = Integer.toBinaryString(N);
int[] index = new int[10];
int idx = 0;
int max = 0;
for(int i=0;i<binary.length();i++){
if(binary.charAt(i)=='1'){
index[idx++]=i;
}
}
if(index.length==1){ return 0; }
else{
for(int i=0;i<index.length;i++){
if(i==index.length-1) return max;
if(index[i+1]-index[i]==1) continue;
else{
int a = index[i+1]-index[i]-1;
if(max<a){
max=a;
}
}
}
return max;
}
}
}
총 2시간이 주어졌으며 나는 103분만에 이 문제를 해결했다. 집에서 집중하는 건 너무 어려워ㅠㅠ
score 가 86점이었는데 이유는 int 배열의 크기를 10으로 설정해서 indexoutofbound 에러가 발생했다.
이미 제출했으니 수정은 불가함ㅠㅠ 흑
1이 들어가 있는 index를 배열에 저장한 후 index의 차를 구해 gap을 구할 수 있었다.
고려해야 할 조건이 많았기 때문에 많은 if문이 들어갔다. 조금 더 깔끔하게 풀 수도 있을 것 같은데 다른 풀이법들을 조금 찾아봐야 할 것 같다.
'프로그래밍 > 알고리즘' 카테고리의 다른 글
[java] 백준 1012번 : 유기농 배추 (bfs, dfs) (0) | 2021.02.19 |
---|---|
[codility] OddOccurrencesInArray 문제풀기 (0) | 2019.09.04 |
[카카오 데모테스트] 직사각형의 좌표 구하기 (0) | 2019.08.26 |