Edward on Java with Leetcode: 2. Add Two Numbers

Edward Zhou
Edward on Java with Leetcode
2 min readNov 25, 2023

Problem

Problem description is available at 2. Add Two Numbers.

Java Solution

The algorithm is straightforward: since a list is a reversed representation of a number and adding should also start from a number’s lower end, I just need to add the corresponding digits from both lists and then move on to the next place until both lists end (if one ends first, its digit will be deemed as 0).

However there are some pitfalls to be aware of:

  1. carry needs to be counted in from the begining ( see below while loop in code), especially if both lists end, the loop may still continue if carry (from last adding) is not 0.
  2. in each iteration, a new node is created (result in below code) and its predecent node (prev in below code) is required to link to the new node, and shortly after result becomes prev (in the eyes of next iteration) it makes sense to have a head that points to the first node and hence return head.next as the final result. In this case, the head is actually a dummy head or a placeholder.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode L1, ListNode L2) {
ListNode head = new ListNode();
ListNode prev = head;
int carry = 0;
while(L1 != null || L2 != null || carry != 0){
int op1 = 0;
int op2 = 0;
if (L1 != null) {
op1 = L1.val;
L1 = L1.next;
}
if (L2 != null) {
op2 = L2.val;
L2 = L2.next;
}
int sum = op1 + op2 + carry;
carry = sum / 10;
ListNode result = new ListNode(sum - carry * 10);
prev.next = result;
prev = result;
}
return head.next;
}
}

Java Knowledge

  1. Logical operator: && and ||, for representing “and” and “or” respectively. Also, in Python, I used to use if (X) to judge if X is None or not. In Java, I have to use if(X != null).
  2. Offical doc Java arithmetic operators definitely worths a read, it includes basic but complete illustrations including operators like
    Modulus or Remainder (%), Increment (++) and decrement (--) and some handy compound assignments like x+=1.

--

--