• [leetcode]2. 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.

    Example:

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

      

    题目:

    用两个链表表示的两个数,求相加之和

    Solution1:  For given two lists, keep looping where either one isn't null. When ListNode comes to null, consider its val as 0.  

                    For result list, use a dummy node.

     

    code:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 /*
    10  Time Complexity:  O(max(l1,l2))
    11  Space Complexity: O(max(l1,l2)) 
    12 */
    13 class Solution {
    14     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    15              ListNode dummy = new ListNode(-1);
    16              ListNode pre = dummy;
    17              ListNode p1 = l1;
    18              ListNode p2 = l2; 
    19              int carry = 0;    
    20              while(p1 != null || p2 != null){
    21                 int x = (p1 != null) ? p1.val : 0; 
    22                 int y = (p2 != null) ? p2.val : 0;
    23                 int sum = carry + x + y; 
    24                 carry = sum / 10;
    25                 // generate the result list
    26                 pre.next = new ListNode(sum % 10);    
    27                  // move three lists pointers  
    28                 pre = pre.next;
    29                 if(p1 != null) p1 = p1.next;
    30                 if(p2 != null) p2 = p2.next;
    31              }
    32              // in case last two digit sum > 10 
    33              if(carry > 0){
    34                  pre.next = new ListNode(carry);
    35              }
    36              return dummy.next;     
    37     }
    38 }
  • 相关阅读:
    docker学习(3) 容器的启动过程
    docker学习(2) mac中docker-machine使用vmware fusion以及配置国内镜像加速
    docker学习(1) 安装
    maven/gradle 打包后自动上传到nexus仓库
    bash/shell编程学习(3)
    jenkins 入门教程(下)
    jenkins 入门教程(中)
    jenkins 入门教程(上)
    bash/shell编程学习(2)
    ssh远程执行目标机器上的命令
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9384224.html
Copyright © 2020-2023  润新知