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

    ## Problem
    
    ### 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.
    
    **Input**: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    
    **Output:** 7 -> 0 -> 8
    
    ## Code
    
    ```
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
         public ListNode addTwoNumbers(ListNode l1, ListNode l2){
            int flag = 0;  //进位符
            ListNode listNode = new ListNode(-1);//头结点,不记录数据
            ListNode Nodetmp = listNode;
            if(l1==null) listNode=l1;//边界条件
            if(l2==null) listNode=l2;
            while(l1!=null||l2!=null){//注意||
                if (l1!=null){//有一个等于null后续都等于null
                    flag+=l1.val;
                    l1 = l1.next;
                }
                if(l2!=null){
                    flag+=l2.val;
                    l2 = l2.next;
                }
                Nodetmp.next = new ListNode(flag%10);
                flag/=10;
                Nodetmp = Nodetmp.next;
            }
            if(flag>0){//next都是null
                Nodetmp.next = new ListNode(flag%10);
            }
            return listNode.next;
        }
    }
    ```
  • 相关阅读:
    二维几何前置知识
    点分治学习笔记
    $fhq-treap$学习笔记
    对拍使用方法
    2021.2.18-2021.5.18 三个月后端开发实习的学习路径
    蓝桥杯常考算法 + 知识点
    Linux
    Linux
    Intern Day112
    Linux上编译运行C/C++程序
  • 原文地址:https://www.cnblogs.com/bingo2-here/p/7141466.html
Copyright © 2011-2022 走看看