LeetCode problem 2. Add Two Numbers

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/efine_dxq/article/details/79077812

问题描述

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.

假定两个数都不是0开头,除了数本身就是0。


例子

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


思路

题目没什么难点,就是链表的顺序遍历问题。注意进位就行了,可能最后有一个进位要再创建一个节点,不要漏掉。


代码

/**
 *  C++ 代码
 * 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) {
        ListNode head(-1);
        int f = 0; //标识进位
        ListNode* pre = &head;
        ListNode* pa = l1, *pb = l2;
        int val = 0, a, b;
        while(pa!=nullptr||pb!=nullptr){

           a = pa == nullptr?0:pa->val;
           b = pb == nullptr?0:pb->val;
           val = a + b + f;
           f = val / 10;
           val = val % 10;

           pre->next = new ListNode(val);

           pa=pa==nullptr?nullptr:pa->next;
           pb=pb==nullptr?nullptr:pb->next;
           pre = pre->next;        
        }
        //最后判断是否有进位
        if(f>0){
          pre->next = new ListNode(f);
        }
        return head.next;
    }
};

猜你喜欢

转载自blog.csdn.net/efine_dxq/article/details/79077812
今日推荐