My 4ms java solution


  • 0
    H
    /**
     * 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 l3 = new ListNode(0);
            ListNode result = l3;
            int curValue = 0;   //currentValue
            int temp = 0;       //over 10 value
            while(l1 != null || l2!= null){
                curValue = l3.val;
                if(l1 != null){
                    curValue += l1.val;
                    l1 = l1.next;
                }
                if(l2 != null){
                    curValue += l2.val;
                    l2 = l2.next;
                }
                temp = curValue / 10;
                l3.val = curValue % 10;
                if(l1 != null || l2 != null || temp == 1){
                    l3.next = new ListNode(temp);
                    l3 = l3.next;
                }
            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.