leetcode题解-2. Add Two Numbers
来源:互联网 发布:网络骗局如何报警 编辑:程序博客网 时间:2024/06/06 00:56
题意:给你两个表示两个非负数字的链表。数字以相反的顺序存储,其节点包含单个数字。将这两个数字相加并将其作为一个链表返回。
例子:输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
解释:342 + 465 = 807.
分析:这道题比较简单,两个链表相加的问题,思路很明确,就是按照位数读下去,维护当前位和进位,时间复杂度是O(n),空间复杂度是O(1).
另外本题是链表部分的第一题,所以也附上链表部分的主函数和打印函数,以后的链表部分题目为了简介不在包含主函数。值得注意的是,因为本题定义了链表节点的数据结构,因此包含Solution.java和ListNode.java两部分的代码。以后为了精简博客,ListNode.java部分的代码也不再附上。
Solution.java
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null && l2 == null) return null; ListNode point = new ListNode(0); ListNode head = point; int carry = 0; while(l1 != null && l2 != null){ int sum = carry + l1.val + l2.val; point.next = new ListNode(sum % 10); point = point.next; carry = sum /10; l1 = l1.next; l2 = l2.next; } while(l1 != null){ int sum = carry + l1.val; point.next = new ListNode(sum % 10); point = point.next; carry = sum /10; l1 = l1.next; } while(l2 != null){ int sum = carry + l2.val; point.next = new ListNode(sum % 10); point = point.next; carry = sum /10; l2 = l2.next; } if(carry != 0){ point.next = new ListNode(carry); } return head.next; } public static void print(ListNode head){ while(head != null){ System.out.println(head.val); head = head.next; } } public static void main(String[] args) { ListNode l1 = new ListNode(2); ListNode l2 = new ListNode(4); ListNode l3 = new ListNode(3); ListNode l4 = new ListNode(5); ListNode l5 = new ListNode(6); ListNode l6 = new ListNode(4); l1.next = l2; l2.next = l3; l4.next = l5; l5.next = l6; print(addTwoNumbers(l1, l4)); }}
ListNode.java
// Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
阅读全文
0 0
- LeetCode题解--2. Add Two Numbers
- 2. Add Two Numbers : LeetCode 题解
- LeetCode题解:2. Add Two Numbers
- leetcode 题解 2. Add Two Numbers
- Leetcode题解 - 2. Add Two Numbers
- LeetCode Algorithms 2. Add Two Numbers 题解
- LeetCode 2. Add Two Numbers 题解
- 2. Add Two Numbers LeetCode题解
- leetcode题解-2. Add Two Numbers
- LeetCode题解:Add Two Numbers
- LeetCode题解:Add Two Numbers
- [LeetCode] Add Two Numbers题解
- 2. Add Two Numbers 题解
- Leetcode题解(Python): 2.Add Two Numbers
- 题解——Leetcode 2. Add Two Numbers 难度:Medium
- LeetCode 题解(26): Add Two Numbers
- LeetCode题解 || Add Two Numbers 问题
- [Leetcode题解]002 Add Two Numbers
- Intel's Haswell Architecture Analyzed: Building a New PC and a New Intel
- AutoCAD .Net 监测工作空间变化
- bzoj1012
- C/C++ -- 分析++和--
- 简要介绍python
- leetcode题解-2. Add Two Numbers
- [Andriod设计模式之旅]——Builder模式
- 基础知识总结
- 十个能让你成为牛逼前端程序猿的特征
- learn python the hard way (personal) -- Ex0
- AutoCAD .Net 不同文档间复制对象
- Batch Normalize的几点说明
- linux就该这么学:rhce考试经验分享
- vs2008 c++ 使用NI的Measurement Studio工具 编译不过