当前位置:网站首页>TOP2两数相加
TOP2两数相加
2022-08-11 05:35: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/
边栏推荐
猜你喜欢

SECURITY DAY06 ( iptables firewall, filter table control, extended matching, typical application of nat table)

HCIA实验

FusionCompute8.0.0实验(1)CNA及VRM安装

TCP 三次握手、四次断开

消息中间件

HCIP OSPF/MGRE综合实验

(3) Software testing theory (understanding the knowledge of software defects)

HCIP BGP建邻、联邦、汇总实验

detectron2,手把手教你训练mask_rcnn

本地yum源搭建
随机推荐
arcgis填坑_3
局域网文件传输
AUTOMATION DAY07 (Ansible Vault, ordinary users use ansible)
ovnif摄像头修改ip
pytorch下tensorboard可视化深坑
uboot sets the default bootdelay
arcgis填坑_1
mysql 中登录报错:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)ERROR
AUTOMATION DAY06( Ansible进阶 、 Ansible Role)
SECURITY DAY04 (Prometheus server, Prometheus monitored terminal, Grafana, monitoring database)
SECURITY DAY05(Kali系统 、 扫描与抓包 、 SSH基本防护、服务安全 )
SECURITY DAY01 (Monitoring Overview, Zabbix Basics, Zabbix Monitoring Services)
文本三剑客——grep过滤
iptables入门
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-8-2
消息中间件
推荐一个好用的IDEA插件---Translation—中英互译
HPC平台搭建
MySQl进阶之索引结构
【LeetCode】1036. 逃离大迷宫(思路+题解)压缩矩阵+BFS