两数相加算法

输入: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);

            }


        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值