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

    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

     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(null == l1)
    15             return l2;
    16         if(null == l2)
    17             return l1;
    18         ListNode head = new ListNode(0);
    19         ListNode ptr = head;
    20         int carry = 0;                                            //进位
    21         while(null != l1 && null != l2){
    22             ListNode temp = new ListNode(l1.val + l2.val);
    23             temp.next = null;
    24             ptr.next = temp;
    25             ptr = ptr.next;
    26             l1 = l1.next;
    27             l2 = l2.next;
    28         }
    29         while(null != l1){
    30             ListNode temp = new ListNode(l1.val);
    31             ptr.next = temp;
    32             temp.next = null;
    33             ptr = ptr.next;
    34             l1 = l1.next;
    35         }
    36         while(null != l2){
    37             ListNode temp = new ListNode(l2.val);
    38             ptr.next = temp;
    39             temp.next = null;
    40             ptr = ptr.next;
    41             l2 = l2.next;
    42         }
    43         //开始进位    
    44         ptr = head.next;
    45         while(null != ptr){
    46             ptr.val = ptr.val + carry;
    47             carry = ptr.val / 10;
    48             ptr.val %= 10;
    49             ptr = ptr.next;
    50         }
    51         if(1 == carry){
    52             ptr = head.next;
    53             while(null != ptr.next)
    54                 ptr = ptr.next;
    55             ListNode temp = new ListNode(1);
    56             temp.next = null;
    57             ptr.next = temp;
    58         }
    59         
    60         return head.next;
    61     }
    62 }
  • 相关阅读:
    Matplotlib绘制漫威英雄战力图,带你飞起来!
    jupyter渲染网页的3种方式
    MySQL全文索引、联合索引、like查询、json查询速度大比拼
    进一步聊聊weight initialization
    深度学习基础(2)
    深度学习基础(1)
    SLAM的前世今生
    深度学习:识别图片中的电话号码(1)
    tf更新tensor/自定义层
    tf训练OTSU
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4120646.html
Copyright © 2011-2022 走看看