MY C++ Solution


  • 0
    class Solution {
    public:
        int getlenth(ListNode* ln){
    		int len = 0;
    		ListNode* temp = ln;
    		while (temp != nullptr){
    			++len;
    			temp = temp->next;
    		}
    		return len;
    	}
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            if (!l1 &&  l2) return l2;
    		if (l1  && !l2) return l1;
    		if (!l1 && !l2) return nullptr;
    		int flag = 0, num = 0, num1 = 0, num2 = 0;
    		int len1 = getlenth(l1);
    		int len2 = getlenth(l2);
    		ListNode* head = len1 >= len2 ? l1 : l2;
    		ListNode* rear = head;
    		int n = len1 >= len2 ? len1 : len2;
    		for (int i = 0; i < n; i++){
    			num1 = (l1 == nullptr) ? 0 : l1->val;
    			num2 = (l2 == nullptr) ? 0 : l2->val;
    			num  = (num1 + num2 + flag) % 10;
    			flag = (num1 + num2 + flag) / 10;
    			rear->val = num;
    			if (i != (n-1)) rear = rear->next;
    			l1 = l1 ? l1->next : nullptr;
    			l2 = l2 ? l2->next : nullptr;
    		}
    		if (flag != 0){
    			ListNode* temp = new ListNode(flag);
    			rear->next = temp;
    			rear = temp;
    		}
    		return head;
        }
    };

Log in to reply
 

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