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