【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 }
复制代码
posted @   SunshineAtNoon  阅读(181)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示