เราจำเป็นต้องเขียนฟังก์ชัน 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