leetcode Add Two Numbers

本文介绍了一种解决两数相加问题的方法,通过链表形式存储数字,并以逆序方式排列各节点的数值。文章提供了一个具体的Java实现案例,展示了如何遍历两个链表进行逐位相加,并处理进位情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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         ListNode temp1,temp2;
15         temp1=l1;
16         temp2=l2;
17         int flag=0;
18         int sum=0,v1=0,v2=0;
19         ListNode res=new ListNode(-1);
20         ListNode curr=res;
21         while (temp1!=null || temp2!=null) {
22             if (temp1==null) {
23                 v1=0;
24             }else {
25                 v1=temp1.val;
26             }
27             if (temp2==null) {
28                 v2=0;
29             }else {
30                 v2=temp2.val;
31             }
32             sum=v1+v2+flag;
33             if (sum>=10) {
34                 sum=sum-10;
35                 flag=1;
36             }else {
37                 flag=0;
38             }
39             ListNode node=new ListNode(sum);
40             curr.next=node;
41             curr=curr.next;
42             if (temp1!=null) {
43                 temp1=temp1.next;
44             }
45             if (temp2!=null) {
46                 temp2=temp2.next;
47             }
48         }
49         if (flag>0) {
50             curr.next=new ListNode(1);
51         }
52         return res.next;
53     }
54 }

 

转载于:https://www.cnblogs.com/birdhack/p/4106680.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值