Time Limit Exceeded


  • 0
    P

    Why is this code throwing Time Limit Exceeded ?
    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

       ListNode resultHead = null;
       ListNode result = resultHead;
       int carry = 0;
       while(l1 != null && l2 != null){
           int value = l1.val+l2.val;
           int valueDivBy10 = (value+carry)%10;
           carry = (value+carry)/10;
           if(result == null){
               result = new ListNode(valueDivBy10);
               resultHead = result;
           }else{
               ListNode temp = new ListNode(valueDivBy10);
               result.next = temp;
               result = temp;
           }
           l1 = l1.next;
           l2 = l2.next;
       }
       while(l1 != null){
           int value = l1.val;
           int valueDivBy10 = (value+carry)%10;
           carry = (value+carry)/10;
           if(result == null){
               result = new ListNode(valueDivBy10);
               resultHead = result;
           }else{
               ListNode temp = new ListNode(valueDivBy10);
               result.next = temp;
               result = temp;
           }
           l1 = l1.next;
       }
       while(l2 != null){
           int value = l2.val;
           int valueDivBy10 = (value+carry)%10;
           carry = (value+carry)/10;
           if(result == null){
               result = new ListNode(valueDivBy10);
               resultHead = result;
           }else{
               ListNode temp = new ListNode(valueDivBy10);
               result.next = temp;
               result = temp;
           }
           l2 = l2.next;
       }
       if(carry > 0){
           ListNode temp = new ListNode(carry);
           result.next = temp;
           result = temp;
       }
       return resultHead;
      

      }
      }


Log in to reply
 

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