【leetcode刷题笔记】2.两数相加

 题目分析:

由于链表是逆序存储的数字,所以直观上从左到右的排序是个、十、百、千...,按照加法的方法,个位相加,满十进一即可。此外需要考虑当最高位相加仍然大于十,要在链接结尾新增一个进位节点。若链表不一样长,需要把长链表的后续链接上。代码如下:

/**
 * 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) {
    var head=null, l3 = null;
    var carry = 0; //进位
    while(l1 || l2) {
        var n1 = l1 ? l1.val : 0;
        var n2 = l2 ? l2.val : 0;
        var sum = n1 + n2 + carry;
        if (!head) {
            head = l3 = new ListNode(sum%10);
        } else {
            l3.next = new ListNode(sum%10);
            l3 = l3.next;
        }
        carry = Math.floor(sum/10); // 当前进位        
        // 下一位
        if (l1) {
            l1 = l1.next;
        }
        if (l2) {
            l2 = l2.next;
        }
    }
    if (carry > 0) { 
        l3.next = new ListNode(carry); // 最高位进位
    }    
    return head;
}

Typescript版本:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let head:ListNode | null = null, l3:ListNode | null = null;
    let carry: number = 0;
    while (l1 || l2) {
        let n1:number = l1 ? l1.val : 0;
        let n2:number = l2 ? l2.val : 0;
        let sum:number = n1 + n2 + carry;
        if (!head) {
            head = l3 = new ListNode(Math.floor(sum%10));
        } else {
            l3.next = new ListNode(Math.floor(sum%10));
            l3 = l3.next;
        }
        carry = Math.floor(sum/10);
        if (l1) {
            l1 = l1.next;
        }
        if (l2) {
            l2 = l2.next;
        }
    }
    if (carry > 0) {
        l3.next = new ListNode(carry);
    }

    return head;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值