Adding Big Numbers

题目描述

We need to sum big numbers and we require your help.
Write a function that returns the sum of two numbers. The input numbers are strings and the function must return a string.
Example
add(“123”, “321”); -> “444”
add(“11”, “99”); -> “110”

Notes

  • The input numbers are big.
  • The input is a string of only digits
  • The numbers are positives

我的代码

function add(a, b) {
  var arra =a.split('');
  var arrb =b.split('');
  var len = a.length > b.length?a.length:b.length;
  var result = [];
  var count = 0;
  for(i=0; i<len; i++){
    var temp;
    if(i>=a.length){
      temp = Number(arrb.pop()) + count;
    }else if(i>=b.length){
      temp = Number(arra.pop()) + count;
    }else{
      temp = (Number(arra.pop()) + Number(arrb.pop())) + count;
    }
    temp >= 10?[temp,count]=[temp-10,1]:count=0;
    result.push(temp);
  }
  result.push(count);
 // console.log(result);
  return result.reverse().join('').replace(/^0+/,'');
//   return Number(a) + Number(b); // Fix this!
}

Clever

function add (a, b) {
 var res = '', c = 0 ;
 a = a.split('');
 b = b.split('');
 while (a.length || b.length || c) { 
  c += ~~a.pop() + ~~b.pop();
  res = c % 10 + res;
  c = c > 9;
 } 
 return res; 
}

Key

1 . 思路是将a和b的最后一位相加,如果相加的结果大于10,取个位数部分,进位值count+1;并将结果放入到数组中。
2 . 要一位一位相加,需要把a和b两个字符串转成字符串数组,用到.split()函数。
3 . 还要注意判断a串和b串哪个更长,最后循环完后需要将最后一次的进位值放入数组。
4 . 以上步骤得到的数组不是最终结果,还要先翻转,再将字符串数组变成字符串,最后用.replace()方法将首位的0去掉。

-------------完-------------