zoukankan      html  css  js  c++  java
  • LeetCode第二题:Add Two Numbers

    You are given two non-empty linked lists representing two non-negative integers. 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.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    给出两个表示两个非负整数的非空链表。整数以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加,并将其作为链接列表返回。

    你可以假设这两个数字不包含任何前导零,除了第0个数字本身。

    Example

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.

    题目本身不难,但是一定要记得最后的进位问题。下面贴下我的代码,代码量偏多,但是我认为比较好理解。

     1  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
     2         ListNode root = new ListNode(0);
     3         ListNode cur = root;//小技巧定义结果的上一个节点,返回时返回root.next
     4         int temp = 0;       //避免要先进行一次初值的计算
     5         while (l1 != null || l2 != null) {
     6             int n1 = 0;
     7             int n2 = 0;
     8             if (l1 != null) {//因为两个数不一定一样长,当一个数为空时,
     9                 n1 = l1.val; //用0计算即可,熟练的同学完全可以用三目运算符解决。
    10                 l1 = l1.next;
    11             }
    12             if (l2 != null) {
    13                 n2 = l2.val;
    14                 l2 = l2.next;
    15             }
    16             ListNode node = new ListNode((n1 + n2 + temp) % 10);
    17             temp = (n1 + n2 + temp) / 10;
    18             cur.next = node;
    19             cur = node;
    20         }
    21         //这段代码千万不要忘记,如果最后有进位,需要添加节点。
    22         //当然简洁的代码是在while循环中while (l1 != null || l2 != null||temp!=0)
    23         //在循环中解决这个问题,我单独列出来,希望大家牢记这一点,如果在面试中漏掉这种情况
    24         //应该会在面试官那里减分的。
    25         if (temp != 0) {
    26             cur.next = new ListNode(temp);
    27         }
    28         return root.next;
    29     }
  • 相关阅读:
    xml解析模块
    python面向对象基础
    python hashlib模块
    os和sys模块
    python反射
    正则表达式re模块
    踩的python列表及for循环一个坑儿
    python序列化模块json和pickle
    python时间模块-time和datetime
    64匹马、8赛道,至少多少轮比赛找出速度最快的4匹马?
  • 原文地址:https://www.cnblogs.com/zhandouBlog/p/8097932.html
Copyright © 2011-2022 走看看