js string sum All In One
big int number add
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2022-03-17
* @modified
*
* @description 2. Add Two Numbers
* @description
* @difficulty Medium
* @complexity O(n)
* @time O(n)
* @augments
* @example
* @link https://leetcode.com/problems/add-two-numbers/
* @link https://leetcode-cn.com/problems/add-two-numbers/
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
function sumString(a1, a2) {
const s1 = a1.reverse();
const s2 = a2.reverse();
let result = [];
let upNum = 0;
// log('s1', s1);
// log('s2', s2);
if(s1.length >= s2.length) {
result = s1;
for (let i = 0; i < s1.length; i++) {
let a = s1[s1.length - i - 1];
let b = s2[s2.length - i - 1] || 0;
// log('\na, b =', a, b, (a + b));
result[s1.length - i - 1] = (a + b + upNum) % 10;
// log('result =', i, JSON.stringify(result));
if((a + b + upNum) >= 10) {
upNum = 1;
} else {
upNum = 0;
}
// log('upNum =', upNum);
}
} else {
result = s2;
for (let i = 0; i < s2.length; i++) {
let a = s2[s2.length - i - 1];
let b = s1[s1.length - i - 1] || 0;
result[s2.length - i - 1] = (a + b + upNum) % 10;
if((a + b + upNum) >= 10) {
upNum = 1;
} else {
upNum = 0;
}
}
}
if(upNum) {
result.unshift(upNum);
}
log('result', result.reverse());
return result.reverse();
}
sumString([9,9,9,9,9,9,9], [9,9,9,9]);
// [8,9,9,9,0,0,0,1]
// sumString([2,4,3], [5,6,4]);
// [7,0,8]
// Explanation: 342 + 465 = 807.
https://leetcode.com/problems/add-two-numbers/
solution
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const log = console.log;
var addTwoNumbers = function(l1, l2) {
const log = console.log;
log(`l1`, l1)
log(`l2`, l2)
var carry = 0;
var sum = 0;
var head = new ListNode(0);
var now = head;
var a = l1;
var b = l2;
while (a !== null || b !== null) {
sum = (a ? a.val : 0) + (b ? b.val : 0) + carry;
carry = Math.floor(sum / 10);
now.next = new ListNode(sum % 10);
now = now.next;
a = a ? a.next : null;
b = b ? b.next : null;
}
if (carry) now.next = new ListNode(carry);
log(`head`, head)
return head.next;
};
Array.at
const arr= [1, 2, 3];
const i = 0;
console.log(arr.at(i));
// 1
const j = -1;
console.log(ar.at(j));
// 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!