以展開形式表示數字 - JavaScript


假設我們得到一個數字 124,並要求編寫一個將此數字作為輸入並返回其展開形式(作為字串)的函式。

124 的展開形式為 −

'100+20+4'

示例

以下是程式碼 −

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));

輸出

以下是控制檯中的輸出 −

100+20+5

更新於:16-Sep-2020

693 瀏覽量

開啟您的職業

完成課程以獲得認證

立即開始
廣告