Efficient or horrifying?


  • 0
    F

    So this was my solution. Complicated looking but I think it's pretty efficient - it doesn't make use of extra variables other than maintaining a pointer to the start of the list to return, and a carry boolean.

    Maybe it's unreadable though...

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode startptr = l1;
            boolean carry = false;
            for (;;) {
                int num = l1.val + ((l2 != null) ? l2.val : 0) + ((carry) ? 1 : 0);
                carry = (num > 9);
                l1.val = num % 10;
                if (l2 != null && (l1.next == null || l2.next == null)) {
                    if (l1.next == null)
                        l1.next = l2.next;
                    l2 = null;
                }
                if (l1.next == null)
                    break;
                l1 = l1.next;
                if (l2 != null)
                    l2 = l2.next;
            }
            if (carry)
                l1.next = new ListNode(1);
            return startptr;
        }
    }
    

Log in to reply
 

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