Why does this code Run Time? Thank you for help.


  • 0
    Z
    /**
    
    • Definition for singly-linked list.

    • struct ListNode {

    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      /
      class Solution {
      public:
      ListNode
      addTwoNumbers(ListNode* l1, ListNode* l2){
      int len1 = 0;
      int len2 = 0;
      int temp = 0;
      int cin = 0;
      ListNode* ans = l1;
      ListNode* temp1 = l1;
      ListNode* temp2 = l2;
      while (temp1 != NULL){
      len1++;
      temp1 = temp1->next;
      }
      while (temp2 != NULL){
      len2++;
      temp2 = temp2->next;
      }
      if (len1 == 0 && len2 == 0){
      ans = NULL;
      }
      else if (len1 == 0){
      ans = l2;
      }
      else if (len2 == 0){
      ans = l1;
      }
      else if (len1 > len2){
      ans = l1;
      while (l2 != NULL){
      temp = (l1->val + l2->val + cin) % 10;
      cin = (l1->val + l2->val + cin) / 10;
      l1->val = temp;
      l1 = l1->next;
      l2 = l2->next;
      }
      while (l1->next != NULL){
      temp = (l1->val + cin) % 10;
      cin = (l1->val + cin) / 10;
      l1->val = temp;
      l1 = l1->next;
      }
      temp = (l1->val + cin) % 10;
      cin = (l1->val + cin) / 10;
      l1->val = temp;
      if (cin){
      ListNode t(cin);
      l1->next = &t;
      }
      }
      else if(len1 < len2){
      ans = l2;
      while (l1 != NULL){
      temp = (l1->val + l2->val + cin) % 10;
      cin = (l1->val + l2->val + cin) / 10;
      l2->val = temp;
      l1 = l1->next;
      l2 = l2->next;
      }
      while (l2->next != NULL){
      temp = (l2->val + cin) % 10;
      cin = (l2->val + cin) / 10;
      l2->val = temp;
      l2 = l2->next;
      }
      temp = (l2->val + cin) % 10;
      cin = (l2->val + cin) / 10;
      l2->val = temp;
      if (cin){
      ListNode t(cin);
      l2->next = &t;
      }
      }
      else{
      ans = l1;
      while (l1->next != NULL){
      temp = (l1->val + l2->val + cin) % 10;
      cin = (l1->val + l2->val + cin) / 10;
      l1->val = temp;
      l1 = l1->next;
      l2 = l2->next;
      }
      temp = (l1->val + l2->val + cin) % 10;
      cin = (l1->val + l2->val + cin) / 10;
      l1->val = temp;
      if (cin){
      ListNode t(cin);
      l1->next = &t;
      }
      }

      return ans;
      }
      };

    I have run this code in vs2013, and the code is passed in the case which is not right in the OJ


Log in to reply
 

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