3_Add Two Numbers

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

#include<iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

int Link2Int(ListNode* pNode)
{
    int Int_Num=0,add=1;
    while(pNode)
    {
        Int_Num=Int_Num+pNode->val*add;
        add=add*10;
        pNode=pNode->next;
    }

    return  Int_Num;
}
ListNode* Int2Link(int &Int_Num)
{
    ListNode *pNode=new ListNode(-1);
    pNode->next=NULL;

    ListNode *ll=pNode;
    ll->val=Int_Num%10;
    Int_Num/=10; 

    while(Int_Num)
    {
        ListNode *pNode1=new ListNode(Int_Num%10);
        pNode1->next=NULL;

        ll->next=pNode1;

        Int_Num/=10;

        ll=ll->next;
    }
    return pNode;
}
//这个方法仅能支持短链表形式,大整数会溢出
ListNode* addTwoNumbers1(ListNode* l1, ListNode* l2) 
{
    if(l1==NULL) return l2;
    if(l2==NULL) return l1;
    int add_sum=Link2Int(l1) + Link2Int(l2);
    return Int2Link(add_sum);
}
//这个方法可以表示大整数
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
{
    ListNode* node1=l1;
    ListNode* node2=l2;
    
    int sum=0;
    
    ListNode* pnode=new ListNode(0);
    ListNode* node=pnode;
    
    while(node1!=NULL||node2!=NULL)
    {
        sum/=10;
        if(node1!=NULL)
        {
            sum+=node1->val;
            node1=node1->next;    
        }
        if(node2!=NULL)
        {
            sum+=node2->val;
            node2=node2->next;    
        }
        
        node->next=new ListNode(sum%10);
        node=node->next;
    }
    if(sum/10==1)
        node->next=new ListNode(1);
    
    return pnode->next;
}

int main()
{
    //ListNode* pNode1=new ListNode(2);
    //ListNode* pNode2=new ListNode(4);
    ListNode* pNode3=new ListNode(9);
    //pNode1->next=pNode2;
    //pNode2->next=pNode3;
    pNode3->next=NULL;
    
    ListNode* pNode4=new ListNode(1);
    ListNode* pNode5=new ListNode(9);
    ListNode* pNode6=new ListNode(9);
    pNode4->next=pNode5;
    pNode5->next=pNode6;
    pNode6->next=NULL;
    
    ListNode* pNode=addTwoNumbers(pNode3,pNode4);
    
    while(pNode)
    {
        cout<<pNode->val;
        if(pNode->next)
            cout<<"->";
        pNode=pNode->next;
    }
    cout<<endl;
    
    return 0;
}

//g++ Add_Two_Numbers.cc -o Add_Two_Numbers
//./Add_Two_Numbers

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值