在javascript中,對錶示數字的字串相加而不進行完整轉換


我們需要編寫一個 JavaScript 函式,輸入為兩個字串 str1 和 str2,它們分別表示兩個數字。

在不將整個字串轉換為相應數字的情況下,我們的函式應計算這兩個字串數字的和,並返回結果作為字串。

例如,

如果兩個字串為:

const str1 = '234';
const str2 = '129';

那麼輸出應為 363。

示例

以下是程式碼:

const str1 = '234';
const str2 = '129';
const addStringNumbers = (str1, str2) => {
   let ind1 = str1.length - 1,
   ind2 = str2.length - 1,
   res = "",
   carry = 0;
   while(ind1 >= 0 || ind2 >= 0 || carry) {
      const val1 = str1[ind1] || 0;
      const val2 = str2[ind2] || 0;
      let sum = +val1 + +val2 + carry;
      carry = sum > 9 ? 1 : 0;
      res = sum % 10 + res;
      ind1--;
      ind2--;
   };
   return res;
};
console.log(addStringNumbers(str1, str2));

輸出

以下是控制檯輸出:

363

更新於:2021 年 1 月 20 日

691 次瀏覽

開啟你 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.