LeetCode 2. Add Two Numbers (两数相加)
2024-08-31 10:34:24
题目标签:Linked List, Math
题目给了我们两个 Linked List, 各代表一个数字,不过顺序的反的。让我们把两个数字相加。
和普通的相加其实差不多,只不过变成了 Linked List, 还是要用到 / 和 %,具体看code。
Java Solution:
Runtime: 2ms, faster than 87%
Memory Usage: 44MB, less than 85%
完成日期:07/05/2019
关键点:利用 / 取得 carry;利用 % 取得 余数
/**
* 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 dummyHead = new ListNode(0);
ListNode cursor1 = l1;
ListNode cursor2 = l2;
ListNode cursor3 = dummyHead; int carry = 0; while(cursor1 != null || cursor2 != null) // go through both list
{
// if node exists, get the value, elsewise, default 0
int num1 = 0;
int num2 = 0; if(cursor1 != null)
num1 = cursor1.val;
if(cursor2 != null)
num2 = cursor2.val; int sum = num1 + num2 + carry; // update carry and sum
carry = sum / 10;
cursor3.next = new ListNode(sum % 10);
cursor3 = cursor3.next; // move both list to next node
if(cursor1 != null)
cursor1 = cursor1.next;
if(cursor2 != null)
cursor2 = cursor2.next;
} // at last, still need to check carry for last digit
if(carry == 1)
cursor3.next = new ListNode(1); return dummyHead.next;
}
}
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
最新文章
- R语言画图,根据正负值画不同颜色,并且画水平线或者垂直线
- 2016.8.14 HTML5重要标签以及属性学习
- println()函数输出int类型返回值错误的问题
- SQL Server中timestamp(时间戳)
- iOS 8版本信息与屏幕尺寸
- 几种流行Webservice框架性能对照
- Krypton Factor
- P1896 [SCOI2005]互不侵犯King
- [.net 面向对象程序设计深入](24)实战设计模式——策略模式(行为型)
- 201521123089 《Java程序设计》第13周学习总结
- 为什么内部类访问的外部变量需要使用final修饰
- 多线程编程 NSOperation
- 浏览器console打印定义样式
- GraphQL,你准备好了么?
- ToString()格式和用法大全,C#实现保留两位小数的方法
- 快排+java实现
- vue-cli新建vue项目安装axios后在IE下报错
- [转]linux文件批量转码
- 用Matlab实现字符串分割(split)
- centos7提示ifconfig command not found解决