【题解】【链表】【Leetcode】Add Two Numbers
2024-10-14 02:43:24
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
思路:乍一看以为是大整数,实则相当简单,比Add Binary还要简单
代码:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
return addTwoDigit(l1,l2,);
}
ListNode *addTwoDigit(ListNode *d1, ListNode *d2, int carry){
int sum = carry;
ListNode *n1 = d1, *n2 = d2;//不要轻易修改输入参数, 尤其是链表问题中
if(d1 != NULL){
sum += d1->val;
n1 = d1->next;
}
if(d2 != NULL){
sum += d2->val;
n2 = d2->next;
}
ListNode *newNode = new ListNode(sum%); if(d1 == NULL && d2 == NULL){
if(sum == )
return NULL;//Avoid test case:{0}, {0} => {0,0}
return newNode;
} ListNode *nextNode = addTwoDigit(n1, n2, sum/);
newNode->next = nextNode;
return newNode;
}
最新文章
- input只能输入数字并限制长度
- str_replace vs preg_replace
- Java dynamical proxy demo
- Sed文本替换一例
- 黄聪:PHP使用Simple_HTML_DOM遍历、过滤及保留指定属性
- MongoDB 学习笔记(五)索引
- 如何提高手机APP的用户体验?
- 【转】PHP获取当前时间、时间戳的各种格式写法汇总[日期时间]
- android TextView实现滚动显示效果
- Wordpress上传文件 “无法建立目录wp-content/uploads/2018/25。有没有上级目录的写权限?”
- uva1025 动态规划
- Mysql中的常用函数:
- China-global view
- 迁移 VMware 虚拟机到 KVM
- ReadWriteLock读写锁(八)
- 2017-12-18python全栈9期第三天第一节之昨天内容回顾与作业讲解用户三次机会再试试
- Nodejs脚手架搭建基于express的应用
- PAT 1092 To Buy or Not to Buy
- centos7 安装网卡
- ”数学口袋精灵“第二个Sprint计划---第二天