zoukankan      html  css  js  c++  java
  • LeetCode 2. 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

     

    【题目分析】
    用两个链表来表示两个非负数的逆序拍列,每个节点包含一个数字。例如:2 -> 4 -> 3代表342,5 -> 6 -> 4代表465,342+465 = 807。求这两个数的和,并用同样的方式返回。

    【思路】
    两数按位相加,只要处理好向后进位即可。当前相加结果 = 链表1数字+链表2数字+前一个进位。

    【java代码】
     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 public class Solution {
    10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    11         if(l1==null) return l2;
    12         if(l2==null) return l1;
    13         
    14         ListNode l3 = new ListNode(0);
    15         ListNode tail = l3;
    16         
    17         int flag = 0;
    18         while(l1!=null || l2!=null){
    19             int num1 = 0, num2 = 0;
    20             if(l1 != null){
    21                 num1 = l1.val;
    22                 l1 = l1.next;
    23             }
    24             if(l2 != null){
    25                 num2 = l2.val;
    26                 l2 = l2.next;
    27             }
    28             int num = num1 + num2 + flag;
    29             flag = num / 10;
    30             num = num % 10;
    31             ListNode node = new ListNode(num);
    32             tail.next = node;
    33             tail = node;
    34         }
    35         if(flag == 1){
    36             ListNode node = new ListNode(1);
    37             tail.next = node;
    38             tail = node;
    39         }
    40         tail.next = null;
    41         return l3.next;
    42     }
    43 }
  • 相关阅读:
    一行code实现ADO.NET查询结果映射至实体对象。
    傻瓜式使用AutoFac
    Asp.Net MVC中捕捉错误路由并设置默认Not Found页面。
    asp.net MVC中实现调取web api
    JavaScript_11_验证
    JavaScript_10_错误
    JavaScript_9_循环
    JavaScript_8_比较,条件语句
    JavaScript_7_运算符
    JavaScript_6_函数
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5986044.html
Copyright © 2011-2022 走看看