πŸ”¦ Lesson 1 | Iterations (JavaScript)

rimmzΒ·2022λ…„ 7μ›” 20일
0

codility

λͺ©λ‘ 보기
1/1
post-thumbnail

πŸ“Œ 문제

BinaryGap

Find longest sequence of zeros in binary representation of an integer.

https://app.codility.com/programmers/lessons/1-iterations/binary_gap/

πŸ“ 문제 풀이

function solution(N) {
  let binaryArray = N.toString(2).split("1"); // 2μ§„μˆ˜ λ³€ν™˜
  let length = binaryArray.map((x) => x.length); // λ°°μ—΄ μ›μ†Œ 길이 확인
  
  // κ°€μž₯ κΈ΄ 길이 μ°ΎκΈ°
  // 배열이 길이가 2개 μ΄ν•˜ 일 경우 '1'κ³Ό '1' 사이에 μžˆλŠ” 것이 μ•„λ‹ˆλ―€λ‘œ 0 λ°˜ν™˜
  let result = binaryArray.length > 2 ? Math.max(...length) : 0;

  return result;
}

🌿 λ‹€λ₯Έ μ‚¬λžŒμ˜ 풀이

function solution(N) {
  const binary = N.toString(2);
  const trimmed = binary.substr(0, binary.lastIndexOf("1") + 1);
  return Math.max(...trimmed.split("1").map((item) => item.length));
}
profile
#μ˜μš•λ„˜μΉ˜λŠ”#πŸ’»#✨#Front-end#πŸ’ͺ🏻

0개의 λŒ“κΈ€