当前位置:网站首页>LeetCode 445. 两数相加 II
LeetCode 445. 两数相加 II
2022-08-10 11:09:00 【水菜笔】
原题网址:https://leetcode.cn/problems/add-two-numbers-ii/submissions/
数字用链表表示,个位在链表尾;对这两个数做加法,返回新的链表
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list1 = reverseList(l1);
ListNode list2 = reverseList(l2);
int mod=0;
ListNode head = null;
while(list1 != null || list2 != null) {
int num1 = list1 == null ? 0: list1.val;
int num2 = list2 == null ? 0: list2.val;
int sum = num1+num2+mod;
mod = sum/10;
ListNode node = new ListNode(sum%10);
node.next = head;
head = node;
list1 = list1 == null ? null : list1.next;
list2 = list2 == null ? null : list2.next;
}
if(mod !=0) {
ListNode node = new ListNode(1);
node.next = head;
head = node;
}
return head;
}
private ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode cur = head;
ListNode first = null;
while(cur != null) {
ListNode next = cur.next;
cur.next = first;
first = cur;
cur = next;
}
return first;
}
边栏推荐
- POJ 1026 Cipher (置换群)
- 基于UiAutomator2+PageObject模式开展APP自动化测试实战
- Since the media hot style title how to write?Taught you how to write the title
- HDU 6040 Hints of sd0061 (技巧)
- [Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
- LeetCode_628_三个数的最大乘积
- 第2章-矩阵及其运算-矩阵运算(2)
- Programmers pursue technology to consolidate basic learning route suggestions
- 三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)
- blocking non-blocking poll mechanism asynchronous
猜你喜欢
自媒体爆款标题怎么写?手把手教你写热门标题
负载均衡原理分析与源码解读
从源码角度分析UUID的实现原理
基于UiAutomator2+PageObject模式开展APP自动化测试实战
How to join We Media, learn about these 5 monetization modes, and make your account quickly monetize
振弦传感器及核心VM系列振弦采集模块
微信小程序提交审核历史版本记录从哪里查看
从脚本到剪辑,影像大师亲授的后期制作秘籍
零基础想自学软件测试,有没有大佬可以分享下接下来的学习书籍和路线?
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
随机推荐
mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
[Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
【勇敢饭饭,不怕刷题之链表】有序链表的合并
Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using
Licking Exercise - 63 Find all anagrams in a string
快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?
leetcode 823. Binary Trees With Factors(因子二叉树)
ViT结构详解(附pytorch代码)
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
从产品维度来看 我们为什么不能完全信任Layer2?
阻塞 非阻塞 poll机制 异步
LeetCode50天刷题计划(Day 17—— 下一个序列(14.50-16.30)
LAXCUS分布式操作系统安全管理
三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)
石墨文档打开文档时快速定位到上次写的位置
第2章-矩阵及其运算-矩阵运算(2)
L2 applications from a product perspective: why is it a playground?
Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
Emulate stm32 directly with proteus - the programmer can be completely discarded
Module 9 - Designing an e-commerce seckill system