leetcode-002 Add Two Numbers

P002-Add-Two-Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路分析

就是两个链表的并行遍历,并不怎么难。

  • 肯定得遍历两个链表
  • 两链表长度相同时,对应位置相加并将进位保留到下一次循环
  • 两链表长度不相同时,往长度较短的链表尾部补零(最高位和现实生活中的数字恰好相反)

代码

java

/***
 * 2 4 3        2 4 3 0     1 2 3 4 0
 * 5 6 4        5 6 4 9     6 7 8 9 9
 * -------      -------     ----------
 * 7 0 8        7 0 8 9     7 9 1 4 0 1
 * 
 * **/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    if (l1 == null)
        return l2;
    if (l2 == null)
        return l1;
    ListNode l = l1;
    ListNode r = l2;
    ListNode ret = new ListNode(0);
    int up = 0;
    int currentVal = 0;
    ListNode last = ret;
    while (l != null || r != null) {

        // 两个链表长度不一致:补零
        if (l == null)
            l = new ListNode(0);
        if (r == null)
            r = new ListNode(0);

        // 当前值:加上进位
        currentVal = (l.val + r.val) + up;

        if (currentVal >= 10) {
            up = currentVal / 10;// 为下一轮提供的进位
            currentVal = currentVal % 10;// 当前值
        } else {
            up = 0;
        }

        // 新节点
        ListNode newNode = new ListNode(currentVal);

        last.next = newNode;
        last = last.next;

        l = l.next;
        r = r.next;
    }
    if (up != 0) {
        last.next = new ListNode(up);
    }
    return ret.next;
}

python

def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    if (not l1) : return l2
    if (not l2) : return l1
    l = l1;r = l2;
    ret = ListNode(0);last = ret
    up = 0;currentVal = 0

    while (l or r):
        if not l:l = ListNode(0)
        if not r:r = ListNode(0)

        currentVal = (l.val + r.val) + up

        if currentVal >= 10:
            up = currentVal / 10
            currentVal = currentVal % 10
        else:
            up = 0

        newNode = ListNode(currentVal)
        last.next = newNode
        last = last.next

        l = l.next
        r = r.next

    # end while

    if up != 0:
        last.next = ListNode(up)

    return ret.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值