当前位置:网站首页>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/
边栏推荐
- HCIA实验
- FusionCompute8.0.0实验(1)CNA及VRM安装
- China Mobile Communications Group Co., Ltd.: Business Power of Attorney
- 【LeetCode】306.累加数(思路+题解)
- 从mask-rcnn到shp
- uboot代码解析1:根据目的找主线
- SECURITY DAY04 (Prometheus server, Prometheus monitored terminal, Grafana, monitoring database)
- AUTOMATION DAY07( Ansible Vault 、 普通用户使用ansible)
- 利用opencv读取图片,重命名。
- MoreFileRename batch file renaming tool
猜你喜欢
随机推荐
Windos10专业版开启远程桌面协助
华为防火墙-7-dhcp
FusionCompute8.0.0实验(1)CNA及VRM安装
lvm multi-disk mount, combined use
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-7-26
CLUSTER DAY01(集群及LVS简介 、 LVS-NAT集群 、 LVS-DR集群)
kill 命令
SECURITY DAY01 (Monitoring Overview, Zabbix Basics, Zabbix Monitoring Services)
文本三剑客——grep过滤
日志收集分析器(ELK)
安装cuda10.2下paddlepaddle的安装
The ramdisk practice 1: the root file system integrated into the kernel
iptables nat
Login error in mysql: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)ERROR
HCIP OSPF动态路由协议
ansible batch install zabbix-agent
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-8-1
visio文件批量转pdf
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-7-29
(2) Software Testing Theory (*Key Use Case Method Writing)