Leetcode: Add Two Numbers (2)

You are given two linked lists representing two non-negative numbers. The digits are stored in order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

43 + 564 = 607

Input: (4 -> 3) + (5 -> 6 -> 4)
Output: 6 -> 0 -> 7

This one is different with the previous one , since the digits here are not stored in reverse order, the first node is the highest digits of a number. Since the length of these two linked list may not be equal, padding 0's should be added to the shorter list if their length are not equal. 

Input: (4 -> 3) + (5 -> 6 -> 4)==== > (0->4 -> 3) + (5 -> 6 -> 4)
Output: 6 -> 0 -> 7

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        int len1 = length(l1);
    	int len2 = length(l2);
		if(len1 < len2)	addPaddingZeros(&l1, len2-len1);
		if(len2 < len1) addPaddingZeros(&l2, len1-len2);
        //std::cout << len1 << " and " << len2 << std::endl;
		int carry = 0;
		ListNode *head = addTwoNumbers(l1, l2, carry);
        if(carry) {
            ListNode *a_node = new ListNode(carry);
            a_node->next = head;
            head = a_node;
        }
        return head;
    }
    
    // here the llinked list l1 and l2 have the equal length.
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2, int &carry) {
        if(l1 == NULL) return NULL;
        
        ListNode *a_node = new ListNode(0);
        a_node->next = addTwoNumbers(l1->next, l2->next, carry);
        int temp = (l1->val + l2->val + carry) % 10;
        carry = (l1->val + l2->val + carry) / 10;
        a_node->val = temp;
        return a_node;
    }
	
	int length(ListNode *head) {
		if (head == NULL) return 0;
		int len = 0;
		while(head) {
			++len;
			head = head->next;
		}
		return len;		
	}
	
	void addPaddingZeros(ListNode **head, int count) {
		if(count == 0 || *head == NULL) return;
		while(count) {
			--count;
			ListNode *dummy_node = new ListNode(0);
			dummy_node->next = *head;
			*head = dummy_node;
		}		
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值