Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การบวกสตริงตัวเลขโดยไม่ใช้เมธอดแปลงชนิดข้อมูลใน JavaScript


ภาพรวม

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงตัวเลขสองสตริง ฟังก์ชันควรบวกตัวเลขในสตริงโดยไม่แปลงเป็นตัวเลขจริงหรือใช้ไลบรารีแปลงชนิดข้อมูล

ตัวอย่าง

const str1 = '123';
const str2 = '456';

ผลลัพธ์ควรเป็น:

const output = '579';

ตัวอย่างโค้ด

const str1 = '123';
const str2 = '456';

const addStrings = (num1, num2) => {
  // ให้แน่ใจว่า num1 ไม่สั้นกว่า num2
  if (num1.length < num2.length) {
    let tmp = num2;
    num2 = num1;
    num1 = tmp;
  }
  let n1 = num1.length;
  let n2 = num2.length;
  let arr = num1.split('');
  let carry = 0;
  let total;
  
  for (let i = n1 - 1, j = n2 - 1; i >= 0; i--, j--) {
    let term2 = carry + (j >= 0 ? parseInt(num2[j]) : 0);
    if (term2) {
      total = parseInt(num1[i]) + term2;
      if (total > 9) {
        arr[i] = (total - 10).toString();
        carry = 1;
      } else {
        arr[i] = total.toString();
        carry = 0;
        if (j < 0) {
          break;
        }
      }
    }
  }
  return (total > 9 ? '1' + arr.join('') : arr.join(''));
};

console.log(addStrings(str1, str2));

ผลลัพธ์ในคอนโซล

579