Leetcode 2. Add Two Numbers
来源:互联网 发布:net域名名站 编辑:程序博客网 时间:2024/06/08 04:36
2. 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
准备把做过的题过一遍。补发之前没有发过题的blog。四个月前做的这个题,博主最近搬家,没怎么刷题了。做了一会的。
不知道是不是老了,居然看了半天example没看懂,主要是给的例子两边都是7,谁知道是哪个方向。后来发现了,就是算一个数放到list尾部。方便很多。
使用一个while循环,当l1 l2 和进位均为null或0的时候就退出循环。
自己做的时候问题如下:
1. 第一遍忘记跳转l1 l2导致TLE。
2. 插入末尾元素两行的代码写着写着就按照插入队中的代码三行写了。
3. 4MS版本多了俩判断强行变5S,看了以前写的又改回了4MS。
public class Solution { // 5ms public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null && l2 == null) return null; if(l1 == null || l2 == null) return l1 == null ? l2 : l1; ListNode head = new ListNode(0); ListNode rear = head; int carry = 0; while(l1 != null || l2 != null || carry != 0){ int a = l1 != null ? l1.val : 0; int b = l2 != null ? l2.val : 0; int temp = a + b + carry; carry = temp >= 10 ? 1 : 0; temp = carry == 1 ? temp%10 : temp; ListNode cur = new ListNode(temp); rear.next = cur; rear = rear.next; l1 = l1 == null ? l1 : l1.next; l2 = l2 == null ? l2 : l2.next; } return head.next; }}
public class Solution { // 4ms public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null && l2 == null) return null; if(l1 == null || l2 == null) return l1 == null ? l2 : l1; ListNode head = new ListNode(0); ListNode rear = head; int carry = 0; while(l1 != null || l2 != null || carry != 0){ int a = l1 != null ? l1.val : 0; int b = l2 != null ? l2.val : 0; int temp = a + b + carry; carry = temp / 10 ; // carry = temp >= 10 ? 1 : 0; temp = temp % 10; // temp = carry == 1 ? temp%10 : temp; ListNode cur = new ListNode(temp); rear.next = cur; rear = rear.next; l1 = l1 == null ? l1 : l1.next; l2 = l2 == null ? l2 : l2.next; } return head.next; }}
0 0
- [LeetCode]2.Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode --- 2. Add Two Numbers
- [Leetcode] 2. Add Two Numbers
- 【leetcode】2. Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode-2.Add Two Numbers
- [leetcode] 2. Add Two Numbers
- 【LeetCode】2. Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode 2. Add Two Numbers
- 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
- 2. Add Two Numbers----LeetCode
- android 使用java 代码设置 textview的图片
- R语言 我要如何开始R语言
- home live buy
- Linux冷门却很重要的命令(二)---pgrep
- win7 64位,PowerDesigner中导入MYSQL数据库结构的步骤及问题解决
- Leetcode 2. Add Two Numbers
- Android Studio代码检测和性能分析工具
- org.apache.catalina.deploy.WebXml addFilter
- poj3070 Fibonacci(矩阵快速幂)
- 【Codeforces Round 364 (Div 2)C】【前缀和 双指针】They Are Everywhere 含有所有字符的最短区间长度
- EEPROM和FLASH区别
- Hdu 3938 Portal((离线+并查集) (★)
- linux使用nfs、portmap服务共享远程磁盘的方法
- linux之cp/scp命令