Add Two Numbers

1,题目要求

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,题目思路

对于这道题,题目是以两个单链表来表示数字,求出二者的加和,并用链表表示。

在这道题上,一开始个人的想法是将两个链表所表示数字给计算出来,进行和,然后再将这个数字转化为对应的单链表。

原理上是可行,不过我们可以用更简单的策略。从链表的形式我们可以得出,链表是从个位开始的,因此,我们只需要按位操作即可。

  • sum = l1->val + l2->val + extra;
  • extra = sum/10;
  • node->val = sum%10;

3,代码实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

int x = []() {
     
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();


class Solution {
     
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
     
        ListNode start(-1); //设置一个头结点
        ListNode* p = &start;
        
        int extra = 0;
        while(l1 != nullptr || l2!= nullptr || extra!= 0){
     
            int l1Val = l1 == nullptr? 0 : l1->val;
            int l2Val = l2 == nullptr? 0 : l2->val;
            
            int sum = l1Val + l2Val + extra;
            extra = sum/10; //获得可能的进位
            
            p->next = new ListNode(sum%10);
            
            l1 = l1 == nullptr?  l1 : l1->next;
            l2 = l2 == nullptr?  l2 : l2->next;
            
            p = p->next;
        }
        return start.next;
    }
};


你可能感兴趣的:(C++OJ,LeetCode,Top100,Liked,Question,LeetCode,Self-Culture,LeetCode,TopInterview,Question,Top,100,Liked,Questions,Top,Interview,Questions)