Algorithm/codewars

Adding Big Numbers 답안

Bonita SY 2021. 3. 30. 20:03
728x90
반응형

문제)

www.codewars.com/kata/525f4206b73515bffb000b21/train/javascript

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

 

내가 푼 답)

function add(a, b) {
  const maxLength = a.length > b.length ? a.length : b.length;
  const newA = a.padStart(maxLength, '0');
  const newB = b.padStart(maxLength, '0');
  
  let flag = false;
  let result = '';
  for(let i=maxLength-1; i >= 0; i--) {
    let sumAb = Number(newA[i]) + Number(newB[i]);
    
    if (flag) {
      sumAb += 1
    }
    
    if (sumAb >= 10) {
      flag = true;
      sumAb -= 10
    } else {
      flag = false;
    }
    
    result = `${sumAb}${result}`;
  }
  
  return flag ? `1${result}` : result;
}

△ BigInt 쓰지 않고!

 

 

테스트 결과)

 

 

마음에 드는 다른 사람 소스)

728x90
반응형