Expressing numbers in expanded form - JavaScript


Suppose we are given a number 124 and are required to write a function that takes this number as input and returns its expanded form as a string.

The expanded form of 124 is −

'100+20+4'

Example

Following is the code −

const num = 125;
const expandedForm = num => {
   const numStr = String(num);
   let res = '';
   for(let i = 0; i < numStr.length; i++){
      const placeValue = +(numStr[i]) * Math.pow(10, (numStr.length - 1 - i));
      if(numStr.length - i > 1){
         res += `${placeValue}+`
      }else{
         res += placeValue;
      };
   };
   return res;
};
console.log(expandedForm(num));

Output

Following is the output in the console −

100+20+5

Updated on: 16-Sep-2020

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements