zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】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


    题解:模拟即可。用carries保存进位,当l1和l2一方为空的时候,余下不为空的链表要单独处理。当l1和l2都为空的时候,如果carries不为空,那么要再单独申请一个链表存放carries,代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    14         if(l1 == null && l2 == null)
    15             return null;
    16         
    17         ListNode kepeler = new ListNode(0);
    18         ListNode head = kepeler;
    19         int carries = 0;
    20         
    21         while(l1 != null && l2 != null){
    22             int sum = carries + l1.val + l2.val;
    23             carries = sum/10;
    24             kepeler.next = new ListNode(sum%10);
    25             kepeler = kepeler.next;
    26             l1 = l1.next;
    27             l2 = l2.next;
    28         }
    29         
    30         while(l1 != null){
    31             int sum = carries + l1.val;
    32             carries = sum/10;
    33             kepeler.next = new ListNode(sum%10);
    34             l1 = l1.next;
    35             kepeler = kepeler.next;
    36         }
    37         
    38         while(l2 != null){
    39             int sum = carries + l2.val;
    40             carries = sum/10;
    41             kepeler.next = new ListNode(sum%10);
    42             l2 = l2.next;
    43             kepeler = kepeler.next;
    44         }
    45         
    46         if(carries != 0)
    47             kepeler.next = new ListNode(carries);
    48         
    49         return head.next;
    50     }
    51 }
  • 相关阅读:
    Ecshop屏幕wap
    SQLite命令
    初识SQLite
    last_insert_id()
    php中的全局变量global(低级错误啊)
    在搜索框加入语音搜索
    解压zip文件出现bash:unzip:commond not found
    DataView.RowFilter使用
    设计自己的模板引擎(一)模板替换中的嵌套循环处理
    没完没了的Cookie,读懂asp.net,asp等web编程中的cookies 
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3856339.html
Copyright © 2011-2022 走看看