当前位置:网站首页>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/
边栏推荐
猜你喜欢

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

HCIP-生成树(802.1D ,标准生成树/802.1W : RSTP 快速生成树/802.1S : MST 多生成树)

grep、sed、awk

MoreFileRename batch file renaming tool

FusionCompute8.0.0实验(0)CNA及VRM安装(2280v2)

lvm multi-disk mount, combined use

八股文之jvm

slurm cluster construction

The ramdisk practice 1: the root file system integrated into the kernel

TOP2两数相加
随机推荐
buildroot嵌入式文件系统中vi显示行号
uboot代码解析1:根据目的找主线
WiFi Deauth 攻击演示分析 // mdk4 // aireplay-ng// Kali // wireshark //
HCIA知识复习
HCIP实验(pap、chap、HDLC、MGRE、RIP)
Threatless Technology-TVD Daily Vulnerability Intelligence-2022-8-3
Solve win10 installed portal v13 / v15 asked repeatedly to restart problem.
buildroot设置dhcp
View the library ldd that the executable depends on
推荐一个好用的IDEA插件---Translation—中英互译
华为防火墙-4-安全策略
ramdisk实践1:将根文件系统集成到内核中
CLUSTER DAY03 (Ceph overview, the deployment of Ceph CLUSTER, Ceph block storage)
China Mobile Communications Group Co., Ltd.: Business Power of Attorney
visio文件批量转pdf
OA项目之待开会议&历史会议&所有会议
八股文之并发编程
(3) Software testing theory (understanding the knowledge of software defects)
iptables的状态
使用路由器DDNS功能+动态公网IP实现外网访问(花生壳)