博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Add Two Numbers
阅读量:6993 次
发布时间:2019-06-27

本文共 1815 字,大约阅读时间需要 6 分钟。

问题描写叙述:

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

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8
解决方式:

/** * 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) {        if(l1==NULL||l2==NULL)            return NULL;        int c = 0;        ListNode* result = new ListNode(0);        ListNode* pNode = result;        pNode->next = NULL;        pNode->val = (l1->val+l2->val)%10;        c = (l1->val+l2->val)/10;        l1 = l1->next;        l2 = l2->next;        while(l1!=NULL&&l2!=NULL)        {            ListNode* temp = new ListNode(0);            temp->next = NULL;            temp->val = (l1->val+l2->val+c)%10;            c = (l1->val+l2->val+c)/10;            pNode->next = temp;            pNode = pNode->next;            l1 = l1->next;            l2 = l2->next;        }        while(l1!=NULL)        {            ListNode* temp = new ListNode(0);            temp->next = NULL;            temp->val = (l1->val+c)%10;            c = (l1->val+c)/10;            pNode->next = temp;            pNode = pNode->next;            l1=l1->next;        }         while(l2!=NULL)        {            ListNode* temp = new ListNode(0);            temp->next = NULL;            temp->val = (l2->val+c)%10;            c = (l2->val+c)/10;            pNode->next = temp;            pNode = pNode->next;            l2=l2->next;        }        if(c)        {            ListNode* temp = new ListNode(c);            pNode->next = temp;        }        return result;    }};

转载地址:http://kawvl.baihongyu.com/

你可能感兴趣的文章
PDM/PLM系统授权模型的研究和应用(转载)
查看>>
Winform下的Datagrid的列风格(4)—DataGridComboBoxTableViewColumn
查看>>
上传图片 以及做成缩略图
查看>>
封装和多态
查看>>
POJ - 3041 Asteroids 【二分图匹配】
查看>>
luogu P4198 楼房重建——线段树
查看>>
使用property为类中的数据添加行为
查看>>
程序设计基础知识
查看>>
复变函数与积分变换
查看>>
12. 断点续传的原理
查看>>
C#基础:多态:基类可以定义并实现虚(virtual)方法,派生类可以重写(override)这些方法...
查看>>
Visifire图表
查看>>
python常用模块之paramiko与ssh
查看>>
AES算法在Python中的使用
查看>>
动手动脑3
查看>>
HDU 3397 Sequence operation(线段树区间染色加区间合并)
查看>>
【随笔】写下现在所想的,开始写博客
查看>>
linux命令之vi文本编辑器
查看>>
WPF-WrapPanel
查看>>
大家好
查看>>