LeetCode01—两数相加

题目描述

LeetCode01—两数相加_第1张图片

主要思路

  • 取余得到当前位,取模得到进位

Java实现

package leetcode;

public class AddTwoNumbers {

    /**
     Input: (2->4->3) + (5->6->4)
     Output: 7->0->8
     Sample: 342 + 465 = 807

     取余得到当前位,取模得到进位
        Time: O(n)
        Space: O(n)
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        int sum = 0;
        ListNode cur = dummy;
        ListNode p1 = l1, p2=l2;
        while (p1 != null || p2 != null) {
            if(p1 != null) {
                sum += p1.val;
                p1 = p1.next;
            }

            if(p2 != null) {
                sum += p2.val;
                p2 = p2.next;
            }

            cur.next = new ListNode(sum % 10);
            sum /= 10;
            cur = cur.next;
        }

        if(sum == 1) {
            cur.next = new ListNode(1);
        }
        return dummy.next;
    }

    public class ListNode{
        int val;

        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
}

你可能感兴趣的:(数据结构与算法,LeetCode)