Jieunny์˜ ๋ธ”๋กœ๊ทธ

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋‹คํ•ญ์‹ ๋”ํ•˜๊ธฐ ๋ณธ๋ฌธ

Study/Coding Test

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋‹คํ•ญ์‹ ๋”ํ•˜๊ธฐ

Jieunny 2023. 2. 6. 10:14

๐Ÿ“Œ  ๋ฌธ์ œ

ํ•œ ๊ฐœ ์ด์ƒ์˜ ํ•ญ์˜ ํ•ฉ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ์‹์„ ๋‹คํ•ญ์‹์ด๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๋‹คํ•ญ์‹์„ ๊ณ„์‚ฐํ•  ๋•Œ๋Š” ๋™๋ฅ˜ํ•ญ๋ผ๋ฆฌ ๊ณ„์‚ฐํ•ด ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ๋ง์…ˆ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹คํ•ญ์‹ polynomial์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๋™๋ฅ˜ํ•ญ๋ผ๋ฆฌ ๋”ํ•œ ๊ฒฐ๊ด๊ฐ’์„ ๋ฌธ์ž์—ด๋กœ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด๋ณด์„ธ์š”. ๊ฐ™์€ ์‹์ด๋ผ๋ฉด ๊ฐ€์žฅ ์งง์€ ์ˆ˜์‹์„ return ํ•ฉ๋‹ˆ๋‹ค.


์ œํ•œ์‚ฌํ•ญ

  • 0 < polynomial์— ์žˆ๋Š” ์ˆ˜ < 100
  • polynomial์— ๋ณ€์ˆ˜๋Š” 'x'๋งŒ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.
  • polynomial์€ 0๋ถ€ํ„ฐ 9๊นŒ์ง€์˜ ์ •์ˆ˜, ๊ณต๋ฐฑ, ‘x’, ‘+'๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ํ•ญ๊ณผ ์—ฐ์‚ฐ๊ธฐํ˜ธ ์‚ฌ์ด์—๋Š” ํ•ญ์ƒ ๊ณต๋ฐฑ์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.
  • ๊ณต๋ฐฑ์€ ์—ฐ์†๋˜์ง€ ์•Š์œผ๋ฉฐ ์‹œ์ž‘์ด๋‚˜ ๋์—๋Š” ๊ณต๋ฐฑ์ด ์—†์Šต๋‹ˆ๋‹ค.
  • ํ•˜๋‚˜์˜ ํ•ญ์—์„œ ๋ณ€์ˆ˜๊ฐ€ ์ˆซ์ž ์•ž์— ์˜ค๋Š” ๊ฒฝ์šฐ๋Š” ์—†์Šต๋‹ˆ๋‹ค.
  • " + 3xx + + x7 + "์™€ ๊ฐ™์€ ์ž˜๋ชป๋œ ์ž…๋ ฅ์€ ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • "012x + 001"์ฒ˜๋Ÿผ 0์„ ์ œ์™ธํ•˜๊ณ ๋Š” 0์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ˆ˜๋Š” ์—†์Šต๋‹ˆ๋‹ค.
  • ๋ฌธ์ž์™€ ์ˆซ์ž ์‚ฌ์ด์˜ ๊ณฑํ•˜๊ธฐ๋Š” ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.
  • polynomial์—๋Š” ์ผ์ฐจ ํ•ญ๊ณผ ์ƒ์ˆ˜ํ•ญ๋งŒ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.
  • ๊ณ„์ˆ˜ 1์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.
  • ๊ฒฐ๊ด๊ฐ’์— ์ƒ์ˆ˜ํ•ญ์€ ๋งˆ์ง€๋ง‰์— ๋‘ก๋‹ˆ๋‹ค.
  • 0 < polynomial์˜ ๊ธธ์ด < 50

 

๐Ÿ’ก  ์•„์ด๋””์–ด

polynomial์„ ๊ณต๋ฐฑ์œผ๋กœ ๋‚˜๋ˆ„๊ณ , x์ธ ๊ฒฝ์šฐ/ + ์ธ ๊ฒฝ์šฐ/ ์ˆซ์ž์ธ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ ์„œ ๋ฐฐ์—ด์— ์ €์žฅํ•œ๋‹ค.

์–ด์ฐจํ”ผ ๋”ํ•˜๊ธฐ๋งŒ ์ฃผ์–ด์ง€๊ธฐ ๋•Œ๋ฌธ์—, x์•ž์˜ ์ˆซ์ž๋ฅผ ๋ชจ๋‘ ๋”ํ•˜๊ณ , ์ˆซ์ž๋Š” ๋”ฐ๋กœ ๋”ํ•ด์„œ x๊ฐ’์€ x๋ฅผ ๋ถ™์—ฌ์„œ answer์— ๋”ํ•ด์ค€๋‹ค.

์ด๋•Œ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ๊ฐ€ '0' ์ผ ๊ฒฝ์šฐ, x์˜ ๊ณ„์ˆ˜๊ฐ€ 1์ด๋‚˜ 0์ผ ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

 

โœ๏ธ  ํ’€์ด

function solution(polynomial) {
  var answer = '';
  let arr = polynomial.split(" ");
  let xArr = [];
  let valueArr = [];
  let xSum = 0;
  let valueSum = 0;
  
    for(let i of arr){
      if(i.includes('x')) xArr.push(i);
      else if(i.includes('x') === false && i !== '+') valueArr.push(i);
    }

    for(let i of xArr){
      let xIndex = i.indexOf('x');
      if(i === 'x') xSum += 1;
      else xSum += Number(i.slice(0, xIndex));
    }

    for(let i of valueArr){
      valueSum += Number(i);
    }

    if(xSum !== 0 && xSum !== 1) answer += `${xSum}x`;
    else if(xSum === 1) answer += 'x';
    else answer += '';

    if(valueSum !== 0 && xSum !== 0) answer += ` + ${valueSum}`;
    else if(valueSum !== 0) answer += `${valueSum}`;
    else answer += '';
  
    if (answer === '') answer += '0';

  return answer;
}