[leetcode题解]02.Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807

给定两个链表表示的数,将两数进行相加,结果也按位保存在一个链表中即可,简单的链表操作题目。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *addOneDigit(struct ListNode *head, int val) {
    struct ListNode *node = calloc(1, sizeof(struct ListNode));
    node->val = val;
    head->next = node;
    head = head->next;
    return head;
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode res;
    int c = 0;
    int a = 0;
    int b = 0;
    int sum = 0;
    struct ListNode *now = &res;
    
    while (l1 != NULL || l2 != NULL) {
        a = 0;
        if (l1 != NULL) {
            a = l1->val;
            l1 = l1->next;
        }
        
        b = 0;
        if (l2 != NULL) {
            b = l2->val;
            l2 = l2->next;
        }
        
        sum = a + b + c;
        c = sum / 10;
        sum = sum % 10;
        
        now = addOneDigit(now, sum);
    }
    
    if (c != 0)
        addOneDigit(now, c);
    
    return res.next;
}

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:[leetcode题解]02.Add Two Numbers

本文链接地址:http://www.iaccepted.net/algorithm/leetcode/175.html

相关文章