美文网首页
2.Add Two Numbers

2.Add Two Numbers

作者: 请离我远点儿 | 来源:发表于2015-04-14 16:20 被阅读957次

    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

    翻译
    有两个代表两组非负数字的链表。两个链表按照逆序排序,并且每一个节点包含一位数字。把两组数加起来,并且返回一个链表。

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

    审题
    1.链表
    2.一位数字
    3.返回链表
    4.根据例子知道,
    Output:7->0->8
    其中
    7=3+4;
    0=4+6;
    8=2+5+1(进位);

    隐藏问题
    链表可能很长很长。。。所以不能总是遍历
    两个链表可能不一样的长度,即有可能有些位不用做加法

    我漏掉分析一个,当长度一样的两个链表,最后一位相加进位了,我们需要把进位补到链表最后。。。

    Input: (5) + (5)
    Output: 0 -> 1
    Mine: 0

    解决方案

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        int carry = 0;
        ListNode pointer = result;
        while (l1 != null || l2 != null) {
            //两个有一个没到头,就继续
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            
            pointer.next = new ListNode(carry%10);
            carry /=10;
            pointer = pointer.next;
            
        }
        
        if (carry > 0) {//记得处理最后的进位。。。
            pointer.next = new ListNode(carry);
        }
        
        return result.next;
    }
    

    https://leetcode.com/submissions/detail/25494001/

    相关文章

      网友评论

          本文标题:2.Add Two Numbers

          本文链接:https://www.haomeiwen.com/subject/crhlfttx.html