[LeetCode2]Add Two Numbers

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

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

Analysis

The idea is simple, add each element of two list with the help of a variable "carry". When both of the lists meet their end, return result.
The key point is to check the carry before return, if carry = 1 the highest bit should be 1, that means add a new node with value "1" to the result list. 
e.g. (9->null) + (1->null) = (0->1->null)
Java

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(-1);
		ListNode head = res;
		int carry = 0;
		while(l1!=null || l2!=null){
			int a1 = l1==null ? 0:l1.val;
			int b1 = l2==null ? 0:l2.val;
			int temp = carry+a1+b1;
			carry = temp/10;
			ListNode cur = new ListNode(temp%10);
			head.next = cur;
			head = head.next;
			l1 = l1==null ? null:l1.next;
			l2 = l2==null ? null:l2.next;
		}
		if(carry>0)
			head.next = new ListNode(carry);
		return res.next;
    }
c++

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    int carry = 0;
    ListNode *result = new ListNode(-1);
    ListNode *head = result;
    ListNode *p1 = l1;
    ListNode *p2 = l2;
    while(p1!=NULL && p2!=NULL){

        int sum = (p1->val+p2->val+carry)%10;
        carry = (p1->val+p2->val+carry)/10;
        ListNode *didgt = new ListNode(sum);
        head->next = didgt;
        head = head->next;
        p1 = p1->next, p2 = p2->next;
    }
    while(p1!=NULL){
        int sum = (p1->val+carry)%10;
        carry = (p1->val+carry)/10;
        ListNode *didgt = new ListNode(sum);
        head->next = didgt;
        head = head->next;
        p1 = p1->next;
    }
    while(p2!=NULL){
        int sum = (p2->val+carry)%10;
        carry = (p2->val+carry)/10;
        ListNode *didgt = new ListNode(sum);
        head->next = didgt;
        head = head->next;
        p2 = p2->next;
    }
    if(carry!=0){
        ListNode *didgt = new ListNode(carry);
        head->next = didgt;
    }
    return result->next;
    }





你可能感兴趣的:(LeetCode,add)