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
原创粉丝点击