๐Ÿ”ฆ Lesson 1 | Iterations (JavaScript)

yerimยท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
console.log(๐Ÿ›๐Ÿง)

0๊ฐœ์˜ ๋Œ“๊ธ€

Powered by GraphCDN, the GraphQL CDN