Skip to content

Latest commit

 

History

History
39 lines (28 loc) · 1.08 KB

write-number-in-expanded-form.md

File metadata and controls

39 lines (28 loc) · 1.08 KB

Write Number in Expanded Form 6 Kyu

LINK TO THE KATA - STRINGS MATHEMATICS ALGORITHMS FUNDAMENTALS

Description

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.

Solution

const expandedForm = number => {
  const numberToString = String(number)
  const numberOfDigits = numberToString.length

  const result = []
  for (let i = 0; i < numberOfDigits; i++) {
    const currentDigit = numberToString[i]

    if (currentDigit === '0') continue

    result.push(`${currentDigit}${'0'.repeat(numberOfDigits - i - 1)}`)
  }

  return result.join(' + ')
}