๋ฌธ์ ๋งํฌ
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ๋ค์ ํฐ ์ซ์
์์ฐ์ n์ด ์ฃผ์ด์ก์ ๋, n์ ๋ค์ ํฐ ์ซ์๋ ๋ค์๊ณผ ๊ฐ์ด ์ ์ ํฉ๋๋ค. ์กฐ๊ฑด 1. n์ ๋ค์ ํฐ ์ซ์๋ n๋ณด๋ค ํฐ ์์ฐ์ ์ ๋๋ค. ์กฐ๊ฑด 2. n์ ๋ค์ ํฐ ์ซ์์ n์ 2์ง์๋ก ๋ณํํ์ ๋ 1์ ๊ฐฏ์๊ฐ ๊ฐ์ต๋
programmers.co.kr
์ ๊ทผ ๋ฐฉ๋ฒ
2์ง๋ฒ์ผ๋ก ๋ณํํ ๋ฌธ์์ด์ 1์ ๊ฐ์๋ฅผ ๋ชจ๋ count ํ๋ ํจ์ countOne()๋ฅผ ๋ง๋ค๊ณ
n์ 1์ฉ ์ฆ๊ฐ์์ผ 2์ง๋ฒ์ผ๋ก ๋ณํํ๊ณ countOne์ ๋ฃ์ด
n.toStirng(2)์ next.toString(2)์ 1์ ๊ฐ์๊ฐ ๊ฐ์ ๋ answer์ ๋ฐํํ์๋ค.
function solution(n) {
var answer = 0;
let next = n+1;
while(next <= 1e6){
const binaryN = n.toString(2);
let nextBinary = next.toString(2);
if(countOne(binaryN) === countOne(nextBinary)){
answer = next;
break;
}
next++;
}
return answer;
}
const countOne = (binary) => {
let cnt = 0;
for(let i = 0; i < binary.length; i++){
if(binary[i] === '1') cnt++;
}
return cnt;
}
'์ฝ๋ฉํ ์คํธ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Javascript] ์ด์ง ๋ณํ ๋ฐ๋ณต (70129) (0) | 2022.06.20 |
---|---|
[Javascript] ์ฌ๋ฐ๋ฅธ ๊ดํธ (12909) (0) | 2022.06.19 |
[Javascript] ์คํฌํธ๋ฆฌ (49993) (0) | 2022.06.18 |
[Javascript] ์ซ์ ๋ธ๋ก (12923) (0) | 2022.06.15 |
[Javascript] ํฐ ์ ๋ง๋ค๊ธฐ (42883) (0) | 2022.06.12 |