Read this and have a nice day [awkward java code that works]


  • 0

    when I first started to answer algorithm questions 2 months ago...

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int carry = 0;
            ListNode head = null;
            ListNode result = null;
            while (l1 != null && l2 != null) {
                int digit = l1.val + l2.val + carry;
                if (digit >= 10) {
                    carry = 1;
                    digit -= 10;
                } else {
                    carry = 0;
                }
                if (head == null) {
                    head = new ListNode(digit);
                    result = head;
                } else {
                    head.next = new ListNode(digit);
                    head = head.next;
                }
                l1 = l1.next;
                l2 = l2.next;
            }
            while (l1 != null) {
                int digit = l1.val + carry;
                if (digit >= 10) {
                    carry = 1;
                    digit -= 10;
                } else {
                    carry = 0;
                }
                if (head == null) {
                    head = new ListNode(digit);
                    result = head;
                } else {
                    head.next = new ListNode(digit);
                    head = head.next;
                }
                l1 = l1.next;
            }
            while (l2 != null) {
                int digit = l2.val + carry;
                if (digit >= 10) {
                    carry = 1;
                    digit -= 10;
                } else {
                    carry = 0;
                }
                if (head == null) {
                    head = new ListNode(digit);
                    result = head;
                } else {
                    head.next = new ListNode(digit);
                    head = head.next;
                }
                l2 = l2.next;
            }
            if (carry != 0) {
                head.next = new ListNode(1);
                head = head.next;
            }
            return result;
        }
    }

Log in to reply
 

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