LeetCode: Add Two Numbers 解题报告
2024-08-28 22:14:56
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
https://oj.leetcode.com/problems/add-two-numbers/
解答:
比较简单,直接用2个指针往后移动,并且将2个list的值相加,并且计算上carry值。注意,在while循环中加上carry == 1的判断,这样可以自动在链尾加上carry 的值。
package Algorithms.list; import Algorithms.algorithm.others.ListNode; /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class AddTwoNumbers {
public static void main(String[] str) {
ListNode n1 = new ListNode(9); ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(9);
ListNode l3 = new ListNode(9);
ListNode l4 = new ListNode(9);
ListNode l5 = new ListNode(9);
ListNode l6 = new ListNode(9);
ListNode l7 = new ListNode(9);
ListNode l8 = new ListNode(9);
ListNode l9 = new ListNode(9);
ListNode l10 = new ListNode(9); l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
l5.next = l6;
l6.next = l7;
l7.next = l8;
l8.next = l9;
l9.next = l10; System.out.println(addTwoNumbers(n1, l1).toString());
} public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return null;
} ListNode dummy = new ListNode(0);
ListNode tail = dummy;
int carry = 0; while (l1 != null || l2 != null || carry == 1) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
} if (l2 != null) {
sum += l2.val;
l2 = l2.next;
} carry = sum / 10; // create a new node and add it to the tail.
ListNode cur = new ListNode(sum % 10);
tail.next = cur;
tail = tail.next;
} return dummy.next;
}
}
代码:
最新文章
- 帝国cmsV6.6版数据表
- mysql 常用
- There was an internal API error.
- Android监听Home键
- 刨根问底U3D---Vector3 你到底是蔬菜呢还是水果呢?
- [py] os.system os.popen commands 执行shell
- 关于 List<;T>;
- 【Android界面实现】FragmentPagerAdapter与FragmentStatePagerAdapter使用详解与区别
- 【JavaScript】apply和call的区别在哪?
- 使用CSS实现一个简单的幻灯片效果
- Linux无线网络设置(wpa_supplicant的使用)
- RelativeLayout的属性详解
- openstack初始化Glance数据库时报错解决方式
- Wireshark显示结果过滤基本语法
- spring拦截器中使用spring的自动注入
- spring入门--spring入门案例
- DNS协议总结
- poj_2553 强连通分支&;出度为0的点
- vue+ivew-admin开发项目,内存占用过大解决办法
- JAVA 之 Tomcat知识框架【转】
热门文章
- java struts2入门学习实例--使用struts2快速实现上传
- 入门程序,hello world
- SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍
- Maven学习--- 搭建多模块企业级项目
- 【javascript】js实现复制、粘贴
- 基于matplotlib的数据可视化 -
- [AaronYang原创] 敏捷开发-Jira 6.0.5环境搭建[1]
- HDU - 4511 小明系列故事――女友的考验(AC自己主动机+DP)
- 【SDOI2014】【BZOJ3529】数表
- PHP的生成器、yield和协程