leetcode------Add Two Numbers

本文介绍了一种使用链表实现加法的方法。对于两个非负数,它们以逆序存储在两个链表中,每个节点包含一个数字。文章提供了一个解决方案,将这两个数相加并返回结果作为一个新的链表。
标题:Add Two Numbers
通过率:22.6%
难度:中等

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         int list1num=-1,list2num=-1;
15         ListNode res=new ListNode(1);
16         ListNode result=res;
17         int carry=0,sum=0;
18         boolean flag=true;
19         while(flag){
20             if(l1!=null&l2!=null){
21                 list1num=l1.val+carry;
22                 list2num=l2.val;
23                 carry=0;
24                 carry=(list1num+list2num)/10;
25                 sum=(list1num+list2num)%10;
26                 ListNode temp=new ListNode(sum);
27                 res.next=temp;
28                 res=temp;
29                 l1=l1.next;
30                 l2=l2.next;
31             }
32             else if(l1!=null&&l2==null){
33                 list1num=l1.val+carry;
34                 carry=0;
35                 carry=list1num/10;
36                 sum=list1num%10;
37                  ListNode temp=new ListNode(sum);
38                 res.next=temp;
39                 res=temp;
40                 l1=l1.next;
41             }
42             else if(l1==null&&l2!=null){
43                  list2num=l2.val+carry;
44                 carry=0;
45                 carry=list2num/10;
46                 sum=list2num%10;
47                  ListNode temp=new ListNode(sum);
48                 res.next=temp;
49                 res=temp;
50                 l2=l2.next;
51             }
52             else {
53                 flag=false;
54                 
55             }
56 
57         }
58         while((carry/10!=0)||(carry%10!=0)){
59              ListNode temp=new ListNode(carry%10);
60              carry=carry/10;
61              res.next=temp;
62              res=temp;
63         }
64         return result.next;
65         
66     }
67 }

 

转载于:https://www.cnblogs.com/pkuYang/p/4322207.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值