<leetcode>Add Two Numbers

来源:互联网 发布:mac 提醒事项 红点 编辑:程序博客网 时间:2024/06/06 03:30

题目描述:

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

Input: (2 -> 4 -> 3) + (5 -> 6-> 4)

Output: 7 -> 0 -> 8

解法:

本题其实是大数按位相加的变形。其中值得注意的是不要忘了进位位可以当独作为一位数输出。如[5],[5],相加等于[0,1]。很容易忘了1的存在得出[0]的错误结果。

/** * 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) {        if(l1 ==NULL)            return l2;        else if(l2 == NULL)        return l1;        ListNode* pHead = new ListNode(0);        pHead->val = 0;        pHead->next = NULL;//表头pHead        ListNode * pNext = pHead;//pNext依序递增链表       int flag = 0, sum = 0;        while( l1 != NULL && l2 != NULL)        {            sum = l1->val + l2->val + flag;            flag = sum / 10;            sum = sum % 10;            pNext->next = new ListNode(sum);//链接链表            pNext = pNext ->next;            l1 = l1->next;            l2 = l2->next;        }        while(l1 != NULL)//我自己很容易写成if(l1 != NULL),一定要注意l1后面也行还有很多值应该直接循环到末尾        {            sum = l1->val + flag;            flag = sum / 10;            sum = sum % 10;            pNext->next = new ListNode(sum);            pNext = pNext ->next;            l1 = l1->next;        }        while(l2 != NULL)        {            sum = l2->val + flag;            flag = sum / 10;            sum = sum % 10;            pNext->next = new ListNode(sum);            pNext = pNext ->next;            l2 = l2->next;        }        if(flag)//!!!当l1和l2位数相等时,千万不用忘了进位位,进位可以单独作为一个数存在!!!        pNext->next = new ListNode(1);      return pHead->next;    }};


0 0