实现两个大数相加

<script>
let a = "9007199254740991";
let b = "1234567899999999999";

function add(a ,b){
   //取两个数字的最大长度
   let maxLength = Math.max(a.length, b.length);
   //用0去补齐长度 padStart第一个参数为长度,第二个为要补全的元素
   a = a.padStart(maxLength , 0);//"0009007199254740991"
   b = b.padStart(maxLength , 0);//"1234567899999999999"
   let t = 0;
   let f = 0;  
   let sum = "";
   for(let i=maxLength-1 ; i>=0 ; i--){
     //遍历他们,十位和十位相加,个位和个位相加,再加上他们进位的数
      t = parseInt(a[i]) + parseInt(b[i]) + f;
      //向下取整
      f = Math.floor(t/10);
      //加上他们的余数
      sum = t%10 + sum;
   }
   if(f == 1){
      sum = "1" + sum;
   }
   return sum;
}
</script>

你可能感兴趣的:(笔记,js)