LeetCode刷题之旅(2)

LeetCode刷题之旅(2)_第1张图片

解决代码:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode p = head;
        if (l1 != null && l2 != null) {
            int jinWei = 0, value = 0;
            while (l1 != null && l2 != null) {
                value = l1.val + l2.val + jinWei;
                ListNode temp = new ListNode(value % 10);
                p.next = temp;
                p = temp;
                jinWei = value / 10;
                l1 = l1.next;
                l2 = l2.next;
            }
            while (l1 != null) {
                value = l1.val + jinWei;
                ListNode temp = new ListNode(value % 10);
                p.next = temp;
                p = temp;
                jinWei = value / 10;
                l1 = l1.next;
            }
            while (l2 != null) {
                value = l2.val + jinWei;
                ListNode temp = new ListNode(value % 10);
                p.next = temp;
                p = temp;
                jinWei = value / 10;
                l2 = l2.next;
            }
            if(jinWei != 0){
                ListNode temp = new ListNode(1);
                p.next = temp;
            }
            return head.next;
        } else {
            return head.next;
        }
    }
}

主要就是需要对加法之后的进位进行考虑,很惊奇发现耗时排名居然在前面,开心~

LeetCode刷题之旅(2)_第2张图片

你可能感兴趣的:(LeetCode)