在 JavaScript 中,求新增兩個數字所需的進位數


問題

我們需要編寫一個 JavaScript 函式,其中包含兩個數字。

我們的函式應統計在紙面上對數字進行相加時所需進位的次數。

如下圖所示,在將 179 和 284 相加時,我們使用了進位兩次,因此對於這兩個數字,我們的函式應返回 2。

範例

以下是程式碼 -

 即時演示

const num1 = 179;
const num2 = 284;
const countCarries = (num1 = 1, num2 = 1) => {
   let res = 0;
   let carry = 0;
   while(num1 + num2){
      carry = +(num1 % 10 + num2 % 10 + carry > 9);
      res += carry;
      num1 = num1 / 10 | 0;
      num2 = num2 / 10 | 0;
   };
   return res;
};
console.log(countCarries(num1, num2));

輸出

以下是控制檯輸出 -

2

更新於: 19-Apr-2021

292 次瀏覽

開啟您的 事業

完成課程後獲得認證

開始
廣告
© . All rights reserved.