LeetCode_2_Add Two Numbers

2. 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

 

题目分析:

  给定两个链表(代表两个非负数),数字的各位以倒序存储,将两个代表数字的链表想加获得一个新的链表(代表两数之和)。

  如(2->4->3)(342) + (5->6->4)(465) = (7->0->8)(807)

 

  设两个进行加法运算的链表分别为l1,l2, sum链表为l3.

  若以l[i] 表示链表各个节点的值,nCarryBit[i]表示l[i]位相加产生的进位符

 

  则有以下结论:

  l3[i] = (l1[i] + l2[i] + nCarryBit[i-1]) % 10

  nCarryBit[i] = (l1[i] + l2[i] + nCarryBit[i-1]) / 10

  且nCarryBit[0] = 0;

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int v1,v2;
        int nCarryBit = 0;
        ListNode* Prehead = new ListNode(0);
        ListNode* l3 = Prehead;
        while(l1 || l2 ||nCarryBit)
        {
            v1 = 0, v2 = 0;
            if(l1)
            {
                v1 = l1->val;
                l1 = l1->next;
            }
            
            if(l2)
            {
                v2 = l2->val;
                l2 = l2->next;
            }
            
            int sum = v1 + v2 +nCarryBit;
            nCarryBit = sum/10;
            l3->next = new ListNode(sum%10);
            l3 = l3->next; 
        }
        return Prehead->next;
    }
};

 

posted @ 2016-04-09 09:43  水月心刀  阅读(134)  评论(0编辑  收藏  举报