在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP