프로그래머스 12939, 70129

박종대·2022년 9월 26일
0

Algorithm

목록 보기
1/3

12939 최댓값과 최솟값

function solution(s) {
    // 공백으로 구분된 숫자, 최대와 최소를 찾자
    const newS = s.split(' ').map((str) => Number(str));
    return `${Math.min(...newS)} ${Math.max(...newS)}`;
}

기억할 점

'test'.split('') -> ['t','e','s','t']
'test'.split('').join('') -> 'test'
Math.max, Math.min -> parameter 개수 제한 없음

70129 이진변환 반복하기

function solution(s) {
    const toBinary = (num) => {
        const binary = [];
        while(num > 1) {
            binary.push(num % 2); 
            num = parseInt(num / 2);
        }
        binary.push(1);
        return binary.reverse().join('');
    }
    const toOne = (str, step, deleteZeroCount) => {
        if(str === '1')
            return [step, deleteZeroCount];
        
        const zeroCount = str.split('').filter((c) => Number(c) === 0).length
        
        return toOne(toBinary(str.split('').length - zeroCount), step+1, deleteZeroCount + zeroCount)
    }
    
    return toOne(s, 0, 0);
}

기억할 점

  • 10진수 -> 2진수 변환
    number가 1보다 같거나 작아질 때 까지 2로 나누면서 2로 나눈 나머지를 결과 string에 저장 후 reverse
  • 정수화 시킬 때 Number() 사용하면 안됨. 실수도 Number이기 때문.
profile
Frontend Developer

0개의 댓글