Super simple C++ && description


  • 4
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* sb = new ListNode(0);          //use a dummy node
            ListNode* result = sb;                                  
            int carry = 0;
            
            while(l1 || l2){                         //while one of them not nullptr
                int tp1 = l1 ? l1 -> val : 0; 
                int tp2 = l2 ? l2 -> val : 0;
                
                int tempInt = (tp1 + tp2 + carry) % 10;    
                carry = (tp1 + tp2 + carry) / 10;  
                sb -> next = new ListNode(tempInt);
                sb = sb -> next;                     //next round
                    
                if(l1) l1 = l1 -> next;
                if(l2) l2 = l2 -> next;
            }
            if(carry) sb -> next = new ListNode(1);  //end digit, if exisit                 
            
            return result -> next;
        }
    };

Log in to reply
 

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