0

In leetcode, for the add two numbers problem, I implemented the same algorithm both in Java and Scala. But Java version outperforms scala a lot. The runtime of java version code is 52ms while the runtime of scala one is 552ms. Why is there huge performance difference?

Codes are attached:

Scala version:

object Solution {
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
var a = l1
var b = l2
var sum = 0
var digit = 0
var tenDigit = 0
val l3 = new ListNode
var c = l3
while(a!=null || b!=null){

  sum = (if(a==null)0 else a._x) + (if(b==null)0 else b._x) + tenDigit
  digit = sum % 10
  tenDigit = sum / 10

  c.next = new ListNode(digit)
  c = c.next
  if(a!=null)a = a.next
  if(b!=null)b = b.next

}

if (tenDigit > 0) {
    c.next = new ListNode(tenDigit);
}

l3.next

}
}

Java version:

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode a = l1;
ListNode b = l2;
int sum = 0;
int digit = 0;
int tenDigit = 0;
ListNode l3 = new ListNode(0);
    ListNode zeroNode = new ListNode(0);
ListNode c = l3;
while(a!=null || b!=null){

sum = (a==null ? 0 : a.val) + (b==null ? 0 : b.val) + tenDigit;
digit = sum % 10;
tenDigit = sum / 10;

c.next = new ListNode(digit);
c = c.next;
if(a!=null)a = a.next;
if(b!=null)b = b.next;

}
if(tenDigit!=0){
   c.next = new ListNode(tenDigit);
}
return l3.next;
}
}
DrunkZemin
  • 51
  • 3

0 Answers0