当前位置:网站首页>TOP2 Add two numbers
TOP2 Add two numbers
2022-08-11 07:08:00 【geekmice】
题目描述
你两个 非空 的链表,表示两个非负的整数.它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字.
请你将两个数相加,并以相同形式返回一个表示和的链表.
你可以假设除了数字 0 之外,这两个数都不会以 0 开头
如图所示
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode(0);
ListNode cursor = root;
int carry = 0;
while(l1 != null || l2 != null || carry != 0) {
int l1Val = l1 != null ? l1.val : 0;
int l2Val = l2 != null ? l2.val : 0;
int sumVal = l1Val + l2Val + carry;
carry = sumVal / 10;
ListNode sumNode = new ListNode(sumVal % 10);
cursor.next = sumNode;
cursor = sumNode;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
return root.next;
}
}
参考地址:https://leetcode.cn/problems/add-two-numbers/comments/
边栏推荐
- 【LeetCode】851.喧闹与富有(思路+题解)
- Threatless Technology-TVD Daily Vulnerability Intelligence-2022-8-3
- Threatless Technology-TVD Daily Vulnerability Intelligence-2022-7-26
- Solve the problem that port 8080 is occupied
- Memory debugging tools Electric Fence
- 利用opencv读取图片,重命名。
- uboot sets the default bootdelay
- 【LeetCode】1036. 逃离大迷宫(思路+题解)压缩矩阵+BFS
- vnc远程桌面安装(2021-10-20日亲测可用)
- SECURITY DAY04 (Prometheus server, Prometheus monitored terminal, Grafana, monitoring database)
猜你喜欢
ovnif摄像头修改ip
cloudreve使用体验
SECURITY DAY06 ( iptables firewall, filter table control, extended matching, typical application of nat table)
grep、sed、awk
window7开启远程桌面功能
Top20括号匹配
HCIP BGP建邻实验
FusionCompute8.0.0 实验(2)虚拟机创建
vi display line number in buildroot embedded file system
VMware workstation 16 installation and configuration
随机推荐
deepin v20.6+cuda+cudnn+anaconda(miniconda)
ETCD Single-Node Fault Emergency Recovery
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-8-1
八股文之并发编程
Arcgis小工具_实现重叠分析
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-7-31
Raspberry Pi set static IP address
华为防火墙-3-应用过滤
华为防火墙-2-状态检测与会话
vnc远程桌面安装(2021-10-20日亲测可用)
Memory debugging tools Electric Fence
slurm集群搭建
(3) Software testing theory (understanding the knowledge of software defects)
iptables的状态
HCIP BGP建邻、联邦、汇总实验
arcmap下的多进程脚本
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-7-26
CLUSTER DAY04(块存储应用案例 、 分布式文件系统 、 对象存储)
FusionCompute8.0.0实验(1)CNA及VRM安装
OA项目之会议通知(查询&是否参会&反馈详情)