Day6 MP-2 Add Two Numbers

一 问题描述

Day6 MP-2 Add Two Numbers_第1张图片

二 问题解决

/**
 * 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) {
        long long num1{0};
        long long num2{0};
        long long  rate{1};
        while(l1 != NULL){
            num1 +=l1->val*rate;
            rate*=10;
            l1=l1->next;
        }
        
        rate = 1;
         while(l2 != NULL){
            num2 +=l2->val*rate;
            rate*=10;
            l2=l2->next;
        }
        
        long long sum =num1+num2;
        
        ListNode *first=new ListNode(sum%10);
        ListNode *last ;
        sum=sum/10;
        last=first;
 
        while(sum > 0){
            ListNode *node = new ListNode(sum%10);
            last->next = node;
            last = node;
            sum = sum / 10;
        }
        return first;
    }
};

题目还没有ac,原因在于大数的问题,需要更改一下数据类型,有时间再改!


Day6 MP-2 Add Two Numbers_第2张图片
存在问题
用链表来每位进行计算,计算后的本位的元素存放在当前节点,然后接到之后的链表中,依次进行,直到最后。
/**
 * 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* l3=new ListNode(-1);
        ListNode* tail =l3;
        ListNode* newtail;
        int flag = 0;
        int value = 0;
        
        while(l1 != NULL && l2 != NULL){
            value = l1->val+l2->val+flag;
            newtail=new ListNode(value%10);
            flag = value/10;
            tail->next=newtail;
            tail=newtail;
            l1=l1->next;
            l2=l2->next;
        }
        while(l1 != NULL){
            value = l1->val+flag;
            newtail=new ListNode(value%10);
            flag = value/10;
            tail->next=newtail;
            tail=newtail;
            l1=l1->next;
        }
          while(l2 != NULL){
            value = l2->val+flag;
            newtail=new ListNode(value%10);
            flag = value/10;
            tail->next=newtail;
            tail=newtail;
            l2=l2->next;
        }
        
        if(flag!=0){
            newtail=new ListNode(flag);
            tail->next=newtail;
            tail=newtail;
        }
         
        return l3->next;
    }
};

bingo,继续加油啦。

你可能感兴趣的:(Day6 MP-2 Add Two Numbers)