본문 바로가기
알고리즘/Codewars

[Codewars] Persistent Bugger. (6 kyu) / JavaScript

by fluss 2022. 11. 30.

https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

 

For example (Input --> Output):

39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
4 --> 0 (because 4 is already a one-digit number)
 

설명:

양의 매개변수를 받고 한자리 수가 될 때까지 숫자를 곱한 횟수를 반환하는 지속성 함수를 작성하세요.

 

예시 (입력 --> 출력):

39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
4 --> 0 (because 4 is already a one-digit number)
 

풀이

숫자를 하나씩 잘라서 모두 곱하고 반복문으로 그 숫자의 길이가 1이 될 때까지 반복하고 그 수를 세서 반환해주었다.

 

코드

function persistence(num) {
  let count = 0;
  num = String(num);
  while(num.length > 1){
    let mul = 1;
    num = num.split('').map(el => parseInt(el));
    for(let i = 0; i < num.length; i++){
      mul *= num[i];
    }
    num = String(mul);
    count += 1
  }
  return count;
}

 

다른 사람의 좋았던 풀이

function persistence(num) {
   var times = 0;
   
   num = num.toString();
   
   while (num.length > 1) {
     times++;
     num = num.split('').map(Number).reduce((a, b) => a * b).toString();
   }
   
   return times;
}

댓글