• 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

    解题思路:

    设立一个头ListNode和尾ListNode,两个List分别从头开始,两两相加并且设立进位carry,如果相加超过10则carry为1,否则为零。同时需要考虑一个List还有长度,另一个已经结束的情况。

    代码如下:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            
    	      ListNode head = new ListNode(0);
    	      ListNode tail = head;
    	      int sum = 0;
    	      int carry = 0;
    	      
    	      while(l1 != null || l2 != null){
    	          if(l1 == null){
    	              sum = l2.val + carry;
    	              l2 = l2.next;
    	          }
    	          else if (l2 == null){
    	              sum = l1.val + carry;
    	              l1 = l1.next;
    	          }
    	          else{
    	              sum = l1.val + l2.val + carry;
    	              l1 = l1.next;
    	              l2 = l2.next;
    	          }
    	          
    	          if(sum >= 10){
    	              carry = sum / 10;
    	              sum = sum % 10;
    	          }
    	          else{
    	              carry = 0;
    	          }
    	          
    	          tail.next = new ListNode(sum);
    	          tail = tail.next;
    	      }
    	      
    	      if(carry != 0){
    	          tail.next = new ListNode(carry);
    	          tail = tail.next;
    	      }
    	      
    	      return head.next;
    	}
    }
    
  • 相关阅读:
    如何下载无水印的抖音视频?
    @valid和自定义异常
    Centos7查看外网ip,yum安装的curl无法正常使用
    ElasticSearch安装
    Redis的主从架构+哨兵模式
    Redis的持久化方式
    Nacos 注册中心集群搭建
    kafka安装流程
    WinUI 3学习笔记(1)—— First Desktop App
    .NET 5学习笔记(12)——WinUI 3 Project Reunion 0.5
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455777.html
Copyright © 2020-2023  润新知