먼저 아래는 Codility의 데모 문제들을 풀어볼 수 있는 사이트입니다.
Developer Training | Test Coding Skills Online - Codility
Find longest sequence of zeros in binary representation of an integer.
app.codility.com
사이트의 첫 번째 문제, BinaryGap (Easy) 입니다.
Easy라고는 하는데 영문으로 된 문제는 처음 풀어봐서 좀 어지럽습니다.
https://app.codility.com/demo/results/trainingFQ7EBE-YTU/
Test results - Codility
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
app.codility.com
신기하더군요. Effective time spent라는 수치도 재서 보여주고...
문제 읽는데 시간이 오래 걸려서 이거 활용도가 높은 수치인진 모르겠습니다.
아무튼 이번 문제는, 숫자 N을 이진수로 바꿔서 1과 다음 1 사이에 0이 최대 몇개 존재하는지 파악하는 문제입니다.
예를 들어 529를 이진수로 바꾸면 1000010001, 즉 0이 연속되는 개수는 4개/3개이고, 최댓값을 구하면 답은 4입니다.
function solution(N) {
let binaryString = "";
let res = 0;
let cnt = 0;
// 이진수로 변환
while (true) {
binaryString += N % 2;
N = Math.floor(N / 2);
if (N <= 1) {
binaryString += N;
break;
}
}
const binaryNums = binaryString.split("").reverse();
// 1과 1 사이 간격의 최댓값 구하기
binaryNums.forEach((num, index) => {
if (index !== 0) {
if (num === "0") {
cnt += 1;
} else {
if (res < cnt) {
res = cnt;
}
cnt = 0;
}
}
});
return res;
}
간단한 문제지만 몰랐던 문법이 몇개 있어서 정리합니다.
- 문자열을 배열로 나누기 위해서는 split("")을 이용한다. split()은 하나하나 나눠지는 게 아닌 전체 문자열이 하나의 인덱스로 들어감.
- 반대로, 배열을 문자열로 합치기 위해서는 join("")을 이용한다.
- 몫을 구하기 위해서는 Math.floor()를 이용한다.
그건 그렇고 .reverse() 메소드가 은근 많이 사용되는군요.
'IT > JavaScript & TypeScript' 카테고리의 다른 글
[JavaScript/알고리즘] OddOccurrencesInArray (feat. Map) (0) | 2025.01.04 |
---|---|
[JavaScript/알고리즘] CyclicRotation (feat. 테스트 케이스) (2) | 2025.01.04 |
[JavaScript/알고리즘] K번째수 (feat. sort() 메소드) (0) | 2024.12.17 |
[TypeScript] 유틸리티 타입 (Partial, Required, Record, Pick, Omit, Exclude) (1) | 2024.12.12 |
[TypeScript] 타입스크립트의 TS7053 오류와 타입 추론 (1) | 2024.11.30 |