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

26、两数相加 #26

Open
conan1992 opened this issue May 8, 2020 · 0 comments
Open

26、两数相加 #26

conan1992 opened this issue May 8, 2020 · 0 comments
Labels

Comments

@conan1992
Copy link
Owner

题目:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let result = new ListNode();
    let next = result;
    let tag = 0;
    while(l1 || l2){
        let x = l1 ? l1.val: 0;
        let y = l2 ? l2.val: 0;
        let sum = x + y + tag;
        tag = Math.floor(sum/10)
        sum = sum%10
        
        next.next = new ListNode();
        next = next.next;
        next.val = sum;
        if(l1){
            l1 = l1.next;
        }
        if(l2){
            l2 = l2.next;
        }
    }
    if(tag){
       next.next = new ListNode(tag); 
    }
    return result.next
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant