[2021-05-05] 여러 자릿수의 숫자를 한자리로 만들기 본문

code/Daily Side Project

[2021-05-05] 여러 자릿수의 숫자를 한자리로 만들기

남우p 2021. 5. 5. 19:17

Question : 
여러 자릿수를 계속 더해서  한자리로 만들어보자.


Answer : 

function digital_root(n) {
  var arr = n;
  var repeat = true;
  while(repeat == true){
    arr = arr.toString().split('').map(x => parseInt(x)).reduce((acc,c) => acc+c);   
    repeat = (arr > 9) ? true : false;
    if(repeat === false){
      return arr;
    }
  } 
}

 

anotherAnswer1 : 

function digital_root(n) {
  var s = 0;
  while (n) {
    s+=n%10;
    n=Math.floor(n/10);
  }
  return s < 10 ? s : digital_root(s);
  
}

 

anotherAnswer2 : 

function digital_root(n) {
  return (n - 1) % 9 + 1;
}

각 자리의 수를 더하는 함수까지 구하고, 9 이상일 때에 이 함수를 추가로 실행하는 방법을 고민했습니다. 수학의 공식으로도 해결할 수 있다는 것을 깨달았습니다.

 

& 이번 작업에서 배운 점 : 

  - 자신의 함수를 내부에서 다시 실행하는 방법

Comments