zoukankan      html  css  js  c++  java
  • Q2:Add Two Numbers

    2. Add Two Numbers

    官方的链接:2. Add Two Numbers

    Description :

    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.

    Example:


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


    问题描述

    给定2个非空的代表非负整数的链表,数字是倒过来存储的,用链表表示求和。可以假设没有前导数字0。

    思路

    使用迭代解法,注意最后的进位。

    [github-here]

     1 public class Q2_AddTwoNumbers {
     2 
     3     /**
     4      * 迭代解法
     5      * 
     6      * @param ListNode
     7      *            l1
     8      * @param ListNode
     9      *            l2
    10      * @return
    11      */
    12     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    13         if (null == l1 && null == l2) {
    14             return new ListNode(0);
    15         }
    16         // 保存链表头,便于创建结点和最后返回结果
    17         ListNode headNode = new ListNode(0);
    18         ListNode sumNode = headNode;
    19         // 和以及进位
    20         int sum = 0;
    21         int carry = 0;
    22         while (null != l1 && null != l2) {
    23             sum = l1.val + l2.val + carry;
    24             sumNode.next = new ListNode(sum % 10);
    25             carry = sum / 10;
    26             sumNode = sumNode.next;
    27             l1 = l1.next;
    28             l2 = l2.next;
    29         }
    30         while (null != l1) {
    31             sum = l1.val + carry;
    32             sumNode.next = new ListNode(sum % 10);
    33             carry = sum / 10;
    34             sumNode = sumNode.next;
    35             l1 = l1.next;
    36         }
    37         while (null != l2) {
    38             sum = l2.val + carry;
    39             sumNode.next = new ListNode(sum % 10);
    40             carry = sum / 10;
    41             sumNode = sumNode.next;
    42             l2 = l2.next;
    43         }
    44         if (carry > 0) {
    45             sumNode.next = new ListNode(carry);
    46             sumNode = sumNode.next;
    47         }
    48         return headNode.next;
    49     }
    50 }
  • 相关阅读:
    Day 03
    Day 03 作业
    Day 02 作业
    Day 02
    Day 01
    Day 10 面向对象基础
    Spring学习-- Bean 的作用域
    一、基本知识
    cloud-init使用技巧
    如何在KVM中管理存储池
  • 原文地址:https://www.cnblogs.com/wpbxin/p/8654114.html
Copyright © 2011-2022 走看看