JSCoding

2021-08-07  本文已影响0人  Mrzhangy

大数相加

const numAdd = (a, b) => {
  // 字符串转换
  a = '0' + a;
  b = '0' + b;
  const len = Math.max(a.length, b.length);
  // 统一长度
  a = a.padStart(len, '0');
  b = b.padStart(len, '0');
 
  let temp = 0;
  let jw = 0; // 进位
  let res = [];
  for (let i = len - 1; i >= 0; i--) {
    temp = Number(a[i]) + Number(b[i]) + jw;
    if (temp >= 10) {
      jw = 1;
      res.unshift((temp + '')[1]);
    } else {
      jw = 0;
      res.unshift(temp);
    }
  }
  return res.join('').replace(/^0/, '');
}

深拷贝

const deepCopy = (obj) => {
  let res;
  if (typeof obj === 'object') {
    for (let i in obj) {
      res[i] = typeof obj[i] === 'object' ? deepCopy(obj[i]) : obj[i];
    }
  } else {
    res = obj;
  }
  return res;
}
上一篇下一篇

猜你喜欢

热点阅读