输入:l1 = [2,4,3], l2 = [5,6,4] 输出:[7,0,8] 解释:342 + 465 = 807.
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
import java.math.BigDecimal;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
StringBuffer str1 = new StringBuffer();
StringBuffer str2 = new StringBuffer();
ListNode init1 = l1;
ListNode init2 = l2;
Integer val = l1.val;
str1.append(val);
Integer val2 = l2.val;
str2.append(val2);
while (true){
ListNode x =init1;
if (null!=x.next){
str1.append(x.next.val);
init1=x.next;
}else {
break;
}
}
while (true){
ListNode x =init2;
if (null!=x.next){
str2.append(x.next.val);
init2=x.next;
}else {
break;
}
}
BigDecimal b1 = new BigDecimal(str1.reverse().toString());
BigDecimal b2 = new BigDecimal(str2.reverse().toString());
BigDecimal add = b1.add(b2);
String s3 = add.toString();
StringBuffer allstr = new StringBuffer();
StringBuffer st3 = new StringBuffer();
st3.append(s3).reverse();
String[] split = st3.toString().split("");
ListNode result =new ListNode(Integer.valueOf(split[0]));
newNode(1, split, result);
System.out.print(result);
return result;
}
public ListNode next(ListNode node){
return node.next;
}
public ListNode newNode(int i,String[] split,ListNode node){
if (i==split.length){
return node;
}else {
node.next=new ListNode(Integer.valueOf(split[i]));
i++;
return newNode(i,split,node.next);
}
}
}