LeetCode——Add Two Numbers
来源:互联网 发布:人工智能的利弊300字 编辑:程序博客网 时间:2024/05/13 02:13
题目
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
思路
很简单,就是对应位置相加,大于等于10的就进位,不过一开始还是犯了一些错误导致时间比较慢,只打败了4%的人。。。主要原因是对next操作,这样就无形多了一些时间。又增加了一个辅助变量p,时间增快了很多打败了80%的人。我这样其实是把最终长度遍历两遍。如果放到一个循环遍历一遍应该还可以增加速度。但是那样代码看起来太复杂了,不便于理解。这样,前面的两个循环做相加,后边一个循环做进位的整理。比较清晰。
解法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = l1 ,p = l1; while (null != l1 && null != l2) { l1.val = l1.val + l2.val ; p = l1 ; l1 = p.next ; l2 = l2.next ; } while(null != l2){ p.next = new ListNode(l2.val); l2 = l2.next ; p = p.next ; } l1 = head ; while(null!=l1){ if (l1.next == null) { l1.next = l1.val>=10 ? new ListNode(1):null ; }else { l1.next.val = l1.val/10+l1.next.val; } l1.val = l1.val%10; l1 = l1.next; } return head ; }}
0 0
- leetcode—Add Two Numbers
- LeetCode —— Add Two Numbers
- LeetCode——Add Two Numbers
- LeetCode——Add Two Numbers
- leetcode 002 —— add two numbers
- LeetCode——Add Two Numbers
- LeetCode——Add Two Numbers
- #2 LeetCode——Add Two Numbers
- LeetCode——Add Two Numbers
- leetcode——Add Two Numbers
- leetcode——2Add Two Numbers
- LeetCode——2. Add Two Numbers
- Leetcode——2. Add Two Numbers
- LeetCode——2. Add Two Numbers
- LeetCode——add two numbers
- LeetCode——2. Add Two Numbers
- Leetcode Problem.2—Add Two Numbers
- LeetCode之2— Add Two Numbers
- LeetCode Contains Duplicate C
- MySQL数据库链接问题及密码修改
- final、finally、finalize
- 传统手动和上电复位电路
- 自绘进度条TProgressbarControl类
- LeetCode——Add Two Numbers
- QT文档的用法
- 还是选择了程序员
- BZOJ 2152: 聪聪可可 点分治/树dp
- vtbl(虚函数表)与vptr(虚函数表指针)
- Java实现员工管理系统(ArrayList+IO写入外部txt)
- 如何解决ORA-04031错误
- 算法导论 使用单链表实现栈
- spring2.5.6与hibernate3.3整合