[Lv.0] 다항식 더하기

01수정·2022년 12월 1일
0
post-thumbnail

<입문 100문제> Day 20 - 수학, 시뮬레이션, 문자열, 사칙연산

문제



풀이

  1. 8, 10, 12 테스트케이스에 실패 : 8,10,12 모두 x 맨 앞의 계수가 1인 경우
function solution(polynomial) {
    let terms = polynomial.replace(/ /gi, '').split('+');
    let sums = terms.reduce(([a,b], term) => {
        if (term.includes('x')) {
            if (term.length === 1) {
                return [a + 1, b];   
            } else {
                return [a + term.replace('x', '')*1, b];
            }
        } else {
            return [a, b + term*1];
        }
    }, [0, 0]);

    if (sums[0] === 0 && sums[1] === 0) {
        return 0;
    }

    if (sums[0] > 0 && sums[1] === 0) {
        return `${sums[0]}x`;
    }

    if (sums[0] === 0 && sums[1] > 0) {
        return `${sums[1]}`;
    }

    if (sums[0] > 0 && sums[1] > 0) {
        return `${sums[0]}x + ${sums[1]}`;
    }
}
function solution(polynomial) {
    let terms = polynomial.replace(/ /gi, '').split('+');
    let sums = terms.reduce(([a,b], term) => {
        console.log('a : ', a, ' b : ', b, ' term : ', term);
        if (term.includes('x')) {
            if (term.length === 1) {
                return [a + 1, b];   
            } else {
                return [a + term.replace('x', '')*1, b];
            }
        } else {
            return [a, b + term*1];
        }
    }, [0, 0]);

    console.log('***', sums[0], ' / ', sums[1]);

    if (sums[0] === 0 && sums[1] === 0) {
        return 0;
    }

    if (sums[0] > 0 && sums[1] === 0) {
        return sums[0] === 1 ? 'x' : `${sums[0]}x`;
    }

    if (sums[0] === 0 && sums[1] > 0) {
        return `${sums[1]}`;
    }

    if (sums[0] > 0 && sums[1] > 0) {
        return `${sums[0] === 1 ? '' : sums[0]}x + ${sums[1]}`;
    }
}

해답

profile
새싹 FE 개발자

0개의 댓글