Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现大整数相加 #257

Open
wuxianqiang opened this issue Mar 29, 2020 · 0 comments
Open

实现大整数相加 #257

wuxianqiang opened this issue Mar 29, 2020 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

wuxianqiang commented Mar 29, 2020

function add (num1, num2) {
  let result = []
  let curry = 0
  let i = num1.length - 1;
  let j = num2.length - 1;
  while (i >= 0 || j >= 0) {
    let n1 = i >= 0 ? Number(num1[i]) : 0;
    let n2 = j >= 0 ? Number(num2[j]) : 0;
    let num = n1 + n2 + curry;
    curry = Math.floor(num / 10);
    result.unshift(num % 10);
    i--;
    j--;
  }
  if (curry === 1) result.unshift(1);
  return result.join('')
}

如果有浮点数,可以拆开计算

function add(num1, num2) {
  let result = []
  let curry = 0
  let i = num1.length - 1;
  let j = num2.length - 1;
  let max = Math.max(i, j);
  while (max >= 0) {
    let n1 = Number(num1[max]) || 0
    let n2 = Number(num2[max]) || 0
    let num = n1 + n2 + curry;
    curry = Math.floor(num / 10);
    result.unshift(num % 10);
    max--;
  }
  return {
    int: curry,
    float: result.join('')
  }
}

function sum(num1, num2) {
  let [a, b = '0'] = num1.split('.')
  let [x, y = '0'] = num2.split('.')
  let { int, float } = add(b, y)
  let total = Number(a) + Number(x) + Number(int)
  float = float.replace(/0+$/g, '')
  if (float) {
    total += `.${float}`
  }
  return total
}

console.log(sum('11.7', '0.3'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant