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

[Codewars] Write Number in Expanded Form (6 kyu) / JavaScript

by fluss 2023. 2. 9.

https://www.codewars.com/kata/5842df8ccbd22792a4000245

 

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 Number in Expanded Form

You will be given a number and you will need to return it as a string in Expanded Form. For example:

expandedForm(12); // Should return '10 + 2'
expandedForm(42); // Should return '40 + 2'
expandedForm(70304); // Should return '70000 + 300 + 4'

NOTE: All numbers will be whole numbers greater than 0.

If you liked this kata, check out part 2!!

 

코드

function expandedForm(num) {
  let result = [];
  while(num){
    let zeros = 1;
    for(let i = 0; i < num.toString().length - 1; i++){
      zeros *= 10;
    }
    let n = Math.floor(num / zeros) * zeros;
    if(n !== 0) result.push(n);
    num = num % zeros;
  }
  return result.join(' + ');
}

댓글