【LetCode 算法修炼】Add Two Numbers
题目
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question
说明:
题目的意思是给出两个整数,它们分别倒序存在链表中,将将它们的和也倒序存在链表中返回。
如例子就是求 342 + 465 = 806,将806倒序存储在链表,返回链表。
解题思路:
遍历两个链表,将val相加的值存到l1,flag 变量作为进位,在结束的时候判断是否有进位,有则加上flag。如果最后一个节点有进位的话则需要new一个节点。
代码:
public class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {if (l1 == null) return l2;if (l2 == null) return l1;ListNode L = l1;ListNode A = new ListNode(0);A.next = l1;int flag = 0;while(l1 != null && l2!= null){l1.val =l1.val +l2.val +flag;flag = l1.val/10;l1.val = l1.val % 10;A = l1;l1 = l1.next;l2 = l2.next;}if(l2 != null){A.next = l2;l1 = l2;}while (l1 != null) { l1.val += flag; flag = l1.val / 10; l1.val = l1.val % 10; A = l1; l1 = l1.next; } if (flag > 0) { ListNode node = new ListNode(1); A.next = node; } return L;}
}
【LetCode 算法修炼】Add Two Numbers相关推荐
- [算法题] Add Two Numbers
题目内容 题目来源:LeetCode You are given two non-empty linked lists representing two non-negative integers. ...
- 【LetCode算法修炼】Two Sum
版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/u013132758. https://blog.csdn.net/u013132758/article/deta ...
- LeetCode 445. Add Two Numbers II--面试算法题--C++,Python解法
题目地址:Add Two Numbers II - LeetCode You are given two non-empty linked lists representing two non-neg ...
- leetcode算法—两数相加 Add Two Numbers
关注微信公众号:CodingTechWork,一起学习进步. 题目 Add Two Numbers: You are given two non-empty linked lists represen ...
- LeetCode算法入门- Add Two Numbers-day3
LeetCode算法入门- Add Two Numbers-day3 Add Two Numbers You are given two non-empty linked lists represen ...
- LeetCode题解:Add Two Numbers
LeetCode题解 说明:本人不是什么算法高手,部分内容参考了Google.stackoverflow.segmentfault中得到的一些解答或者代码.之所以去做Leetcode上的题是因为毕业工 ...
- LeetCode久不久来一题系列之Add Two Numbers
题目来源: https://leetcode.com/problems/add-two-numbers/description/ 题目: Add Two Numbers 题目描述: You are g ...
- [Leetcode] 445. Add Two Numbers II
问题: https://leetcode.com/problems/add-two-numbers-ii/#/description 思路:该题与"415. Add Strings" ...
- LeetCode之Add Two Numbers
LeetCode之Add Two Numbers 题目:You are given two linked lists representing two non-negative numbers. Th ...
最新文章
- Redis初学:11(Redis的配置文件)
- Kafka: Connect
- 在sql server里,日期字段按天数进行group by查询的方法
- anaconda如何更改环境配置_Anaconda环境配置2020-08-27
- Nim游戏(初谈博弈)
- java随机抽题系统_什么样的考试场景需要使用随机试卷模式?
- Mac安装jadx查看dex文件
- 「每天一道面试题」对象和GC Roots引用链没连接时一定会被回收吗
- 数据库范式那些事[转]
- VC运行库合集下载,含VC2005/2008/2010/2012/2013
- FPGA/数字IC秋招笔试面试003——FSM有限状态机、三段式状态机(2022届)
- Java项目:房产中介管理系统(java+SSM+HTML+bootstrap+layui+Mysql)
- 蓝湖及PS测量设计稿的使用
- 接口测试准备一、 网路基础 常用代理工具 charles使用 Android手机代理抓包
- HPM6750EVK 硬件通读与例程通跑 1
- 电灯泡实验应该怎么做_物理小实验 教你测量小灯泡的电功率的方法
- 如何选择技术方向和编程语言
- 服务式办公室出租,保证创业效率
- STM32的USART_GetFlagStatus和USART_GetITStatus解析
- Mac版本VSCode 如何设置中文语言环境