Need help!


  • 0
    W

    Why my code doesn't work?

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            
            if(l1==nullptr && l2==nullptr){
                return nullptr;
            }
            else if(!l1) {
                return l2;
            }
            else if(!l2) {
                return l1;
            }
            
            string num1_s = "";
            string num2_s = "";
            
            while(l1!=nullptr){
                num1_s = to_string(l1->val) + num1_s;
                l1 = l1->next;
            }
            
            while(l2!=nullptr){
                num2_s = to_string(l2->val) + num2_s;
                l2 = l2->next;
            }
            
            int num1 = stoi(num1_s);
            int num2 = stoi(num2_s);
            
            int sum = num1+num2;
            
            string res = to_string(sum);
            
            int size = res.length();
            
            ListNode resHead(res[size-1]-'0');
            
            ListNode *temp = &resHead;
            
            for(int i=size-2; i>= 0; i--) {
                ListNode newTemp(res[i]-'0');
                temp->next = &newTemp;
                temp = temp->next;
            }
            
            return &resHead;
        }
    

Log in to reply
 

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