LeetCode-2.两个列表相加Add Two Numbers --Java

题目: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

这个问题很多同学都是用链表的概念来进行求解的,本文利用BigDecimal从 链表转数字 -> 求和 -> 数字结果转链表 的思路出发来求解该问题

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 import java.math.BigDecimal;
10 import java.util.ArrayList;
11 import java.util.List;
12 import java.util.Collections;
13 public class Solution {
14     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
15     
16         List<Integer> num1 = new ArrayList<Integer>();
17         List<Integer> num2 = new ArrayList<Integer>();
18         BigDecimal add1 = new BigDecimal(0);
19         BigDecimal add2 = new BigDecimal(0);
20         //遍历链表存储至List
21         while(l1!=null){
22             num1.add(l1.val);
23             l1 = l1.next;
24         }
25         while(l2!=null){
26             num2.add(l2.val);
27             l2 = l2.next;
28         }
29         Collections.reverse(num1);
30         Collections.reverse(num2);
31         //遍历两个List求出两个链表对应的整数
32         for(int i=0;i<num1.size();i++){
33             BigDecimal s = new BigDecimal(1);
34             for(int j=0;j<num1.size()-i-1;j++){
35                 s = s.multiply(new BigDecimal(10));
36             }
37             s = s.multiply(new BigDecimal(num1.get(i)));
38             add1 = add1.add(s);
39         }
40         for(int i=0;i<num2.size();i++){
41             BigDecimal s1 = new BigDecimal(1);
42             for(int j=0;j<num2.size()-i-1;j++){
43                 s1 = s1.multiply(new BigDecimal(10));
44             }
45             s1 = s1.multiply(new BigDecimal(num2.get(i)));
46             add2 = add2.add(s1);
47         }
48         //求和
49         BigDecimal add3 = add1.add(add2);
50         String str = String.valueOf(add3);
51         //结果转链表
52         ListNode result = new ListNode(0);
53         ListNode result1 = result;
54         for(int i=0;i<str.length();i++){
55             int m = str.length()-i;
56             int numbers = Integer.parseInt(str.substring(m-1,m));
57             ListNode li = new ListNode(numbers);
58             result.next = li;
59             result = result.next;
60 
61 
62         }
63         return result1.next;
64     }
65 }

 

转载于:https://www.cnblogs.com/smilecoder/p/7040886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值