Simple java solution


  • 0
    T
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(0);
            ListNode tail = head;
            int increase = 0;
            while(l1!=null || l2!=null){
                if(l1!=null){
                    increase += l1.val;
                    l1 = l1.next; 
                }
                if(l2!=null){
                    increase += l2.val;
                    l2 = l2.next;
                }
                if(increase>=10){
                    ListNode temp = new ListNode(increase%10);
                    tail.next = temp;
                    tail = tail.next;
                    increase = 1;
                }else{
                    ListNode temp = new ListNode(increase);
                    tail.next = temp;
                    tail = tail.next;
                    increase = 0;
                }
            }
            if(increase == 1){
                ListNode temp = new ListNode(1);
                tail.next = temp;
            }
            head = head.next;
            return head;
        }
    }

Log in to reply
 

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