Implement an add method to calculate the addition or multiplication of two larger numbers

Implementing a JavaScript function that can handle the addition or multiplication of larger numbers can involve working with large integers. In JavaScript, the range of numbers is limited, but you can use strings to represent large integers.

Below is a simple JavaScript function that handles the addition and multiplication of two large integers. It is assumed here that the input number is a non-negative integer.

Ideas

The units digit is added, and when the number reaches 10, the bit becomes 0. The tens digit is added, and when the number reaches 10, the bit becomes 0, and so on.

If there are not enough digits to add 0, for example, 9999+12, it is equivalent to 9999+0012

function add(a, b) {
    
    
  // 补齐位数,使两个数字长度相等
  while (a.length < b.length) {
    
    
    a = '0' + a;
  }
  while (b.length < a.length) {
    
    
    b = '0' + b;
  }

  let carry = 0; // 进位
  let result = '';

  // 从末尾开始逐位相加
  for (let i = a.length - 1; i >= 0; i--) {
    
    
    const sum = parseInt(a[i]) + parseInt(b[i]) + carry;
    carry = Math.floor(sum / 10); // 计算进位
    result = (sum % 10) + result; // 将当前位的结果添加到最前面
  }

  // 处理最高位的进位
  if (carry > 0) {
    
    
    result = carry + result;
  }

  return result;
}

function multiply(a, b) {
    
    
  let result = '0';

  // 从低位到高位逐位相乘
  for (let i = a.length - 1; i >= 0; i--) {
    
    
    let tempResult = '';
    let carry = 0;

    // 乘法的核心逻辑
    for (let j = b.length - 1; j >= 0; j--) {
    
    
      const product = parseInt(a[i]) * parseInt(b[j]) + carry;
      carry = Math.floor(product / 10);
      tempResult = (product % 10) + tempResult;
    }

    // 处理最高位的进位
    if (carry > 0) {
    
    
      tempResult = carry + tempResult;
    }

    // 在当前位之后添加零,类似于小学的竖式乘法
    for (let k = a.length - 1; k > i; k--) {
    
    
      tempResult = tempResult + '0';
    }

    // 相加得到最终结果
    result = add(result, tempResult);
  }

  return result;
}

// 示例
const num1 = '987654321987654321';
const num2 = '123456789123456789';

console.log(add(num1, num2));      // 输出 '1111111111111111110'
console.log(multiply(num1, num2)); // 输出 '121932631112635269095498763473798607301'

This is a simple implementation, and in practice a library that handles large integers may provide better performance and more functionality.

Supongo que te gusta

Origin blog.csdn.net/m0_46672781/article/details/134813102
Recomendado
Clasificación