zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    Java中List集合去除重复数据的六种方法
    常见的Redis面试"刁难"问题,值得一读
    以Integer类型传参值不变来理解Java值传参
    Linux系统安装snmp服务
    直接取数据到RANGE
    SAP翔子_2019集结号
    销售订单BOM组件分配(CP_BD_DIRECT_INPUT_PLAN_EXT)
    SAP翔子_webservice篇索引
    函数篇3 EXCEL导入函数去除行数限制
    ABAP基础篇4 常用的字符串操作语法
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9384224.html
Copyright © 2011-2022 走看看