题目标签: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/

最新文章

  1. R语言画图,根据正负值画不同颜色,并且画水平线或者垂直线
  2. 2016.8.14 HTML5重要标签以及属性学习
  3. println()函数输出int类型返回值错误的问题
  4. SQL Server中timestamp(时间戳)
  5. iOS 8版本信息与屏幕尺寸
  6. 几种流行Webservice框架性能对照
  7. Krypton Factor
  8. P1896 [SCOI2005]互不侵犯King
  9. [.net 面向对象程序设计深入](24)实战设计模式——策略模式(行为型)
  10. 201521123089 《Java程序设计》第13周学习总结
  11. 为什么内部类访问的外部变量需要使用final修饰
  12. 多线程编程 NSOperation
  13. 浏览器console打印定义样式
  14. GraphQL,你准备好了么?
  15. ToString()格式和用法大全,C#实现保留两位小数的方法
  16. 快排+java实现
  17. vue-cli新建vue项目安装axios后在IE下报错
  18. [转]linux文件批量转码
  19. 用Matlab实现字符串分割(split)
  20. centos7提示ifconfig command not found解决

热门文章

  1. 【Flutter学习】基本组件之容器组件Container
  2. phpMailer 手册
  3. CSS:CSS 轮廓(outline)
  4. hibernate使用手写sql以及对结果list的处理
  5. Feign 系列(04)Contract 源码解析
  6. phoenix 利用CsvBulkLoadTool 批量带入数据并自动创建索引
  7. 在linux 下查询某个进程被那个程序占用
  8. 根据不同运行环境配置和组织node.js应用
  9. 9-MySQL-Ubuntu-数据表中数据的修改(二)
  10. 前端 Java Python等资源合集大放送