728x90
반응형
문제

내 풀이
function solution(n) {
let hex = [...n.toString(2)]
let count = 0;
hex.filter(x=> x==="1" ? count +=1 : "");
let minCount = 0;
let i = n+1;
while(true){
let min = [...i.toString(2)]
min.filter(x=> x==="1" ? minCount +=1 : "")
if (count === minCount){
break;
}
minCount = 0
i+=1
}
return i
}
filter / map 안에 삼항자를 돌려 1의 갯수를 구했고
while 문을 사용해 count === minCount 가 같을 때 break 를 해주었다
그리고 chatGPT 에게 리팩토링👇을 시켜보았다
function findNextNumberWithSameBits(n) {
const binaryDigits = n.toString(2);
const bitCount = binaryDigits.split('1').length - 1;
let nextNumber = n + 1;
while (true) {
const nextBinaryDigits = nextNumber.toString(2);
const nextBitCount = nextBinaryDigits.split('1').length - 1;
if (bitCount === nextBitCount) {
break;
}
nextNumber++;
}
return nextNumber;
}
성능상으론 큰 차이 없지만
좀 더 가독성 좋은 코드로 고쳐주었다
//before
let count = 0;
hex.filter(x=> x==="1" ? count +=1 : "");
//after
const bitCount = binaryDigits.split('1').length - 1;
그리고 좋아요가 가장 많은 풀이
function solution(n,a=n+1) {
return n.toString(2).match(/1/g).length == a.toString(2).match(/1/g).length ? a : solution(n,a+1);
}
정규식 + 재귀
2진수로 바꾸고 안에 들어있는 1을 배열에 담아 배열 length를 각각 구한 후
둘이 일치하면 값을 리턴하고 아니라면 다시(a+1)로 함수를 돌리는 풀이!
별 거 아니지만 정규식은 멋진 거 같답
.match(/1/g)
728x90
반응형
'TIL' 카테고리의 다른 글
git은 파일명/폴더명 대소문자 구별 못함 (1) | 2023.04.29 |
---|---|
웹 최적화 - Image LazyLoading (0) | 2023.04.17 |
코드 스플리팅 (0) | 2023.04.16 |
next.js 학습 (1) (0) | 2023.04.14 |
2023.03.26, weekly memoirs (0) | 2023.03.26 |
댓글