728x90
https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
BinaryGap coding task - Learn to Code - Codility
Find longest sequence of zeros in binary representation of an integer.
app.codility.com
영어라서 쫄았는데 굉장히 쉬웠다.
35분 걸렸고 100점
public class Solution {
public int solution(int N) {
// Implement your solution here
//the max number of 0
int max = 0;
//make binary representation of N
String bin = Integer.toBinaryString(N);
//yield longest bg
int cntZero = 0;
for(int i=0;i<bin.length();i++) { //max length of bin is 32
if(bin.charAt(i)=='1') {
//renewal max
max = Math.max(cntZero, max);
cntZero = 0;
}else {
cntZero++;
}
}
return max;
}
}
1. 숫자 N을 이진수 표현의 String으로 만듦 => Integer.toBinaryString(N) 사용
2. 현재 i에 있는 문자가 1 혹은 0이다
2-1. 1인 경우:
최대 0 개수(max)를 여태까지 나온 0 개수(cntZero)와 비교해서 갱신한다.
여태까지 나온 0 개수를 0개로 초기화한다.
2-2. 0인 경우:
여태까지 나온 0 개수를 하나 늘린다.
728x90
'공부 > Algorithms w.Java' 카테고리의 다른 글
백준 - 아기 상어; Java (0) | 2023.07.01 |
---|---|
Codility NailingPlanks; Java (0) | 2023.07.01 |
java.lang.String.compareTo() 사용법 (0) | 2023.06.29 |
프로그래머스 - 단어 변환; Java (0) | 2023.06.29 |
프로그래머스-정수 삼각형; Java (0) | 2023.06.29 |