# Add two numbers, java 388ms. How to optimize or decrease run time?

• Any suggestions on how to optimize or decrease run time?
Any other suggestions, comments, criticism is welcome.

``````  public class Solution {
ListNode l3;
ListNode h3;
boolean  remainder;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

if(l1 == null && l2 == null)
return null;

while(l1 != null || l2 != null || remainder){
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
return h3;
}

protected void addNode(ListNode l1, ListNode l2){
byte addResult = (byte) ((l1 != null)? l1.val : 0);
addResult += (byte) ((l2 != null)? l2.val : 0);
if(remainder)

if(remainder)
else
}

if(l3 == null){
h3 = l3;
}
else{
l3 = l3.next;
}
}
}``````

• our solutions are similar but I guess the function addNewNodeToList(int addResult) is not necessary.
this function here will check if(l3 == null) every time.
instead, you can initialize h3 = new ListNode(0) and set l3 = h3 before the while loop.
and each time you got a new node you can just append it to l3 and update l3=l3.next
After you finish everything, you can just return h3.next

the code will looks like:

``````    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

if(l1 == null)
return l2;
if(l2 == null)
return l1;  //I also changed the code here a little

ListNode h3 = new ListNode(0);
ListNode l3 = h3;

while(l1 != null || l2 != null || remainder){