Easiest Java Solution, 3 ms.


  • 1
    S

    This code should be straightforward to understand. Let me know if you do not understand this.
    Thank you.

    public class Solution {
        public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1 == null) {
                return l2;
            }
            if(l2 == null) {
                return l1;
            }
        
            ListNode cur1 = l1, cur2 = l2, result = new ListNode(-1), curResult = result;
        
            int sum = 0, carry = 0;
        
            while(cur1 != null || cur2 != null) {
                sum = (cur1 == null ? 0 : cur1.val) + (cur2 == null ? 0 : cur2.val) + carry;
                carry = sum / 10;
                sum %= 10;
            
                curResult.next = new ListNode(sum);
                curResult = curResult.next;
                cur1 = cur1 == null ? null : cur1.next;
                cur2 = cur2 == null ? null : cur2.next;
            }
            
            if(carry == 1) {
                curResult.next = new ListNode(carry);
            }
            return result.next;
        }
    }
    

Log in to reply
 

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