两数相加——leetcode

题目:

  • 2.两数相加
  • 给你两个非空的链表,表示两个非负的整数。它们每位数字都是按逆序的方式存储的,并且每个节点只能存储一位数字。
  • 请你将两个数相加,并以相同形式返回一个表示和的链表。
  • 你可以假设除了数字 0 之外,这两个数都不会以 0开头。

代码

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.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tmp =null;
        int carry = 0;
        while (l1!= null||l2!=null) {
            int n1 = l1!=null?l1.val:0;
            int n2 = l2 !=null?l2.val:0;
            int sum = n1 + n2 + carry;
            if(head==null){
                head = tmp = new ListNode(sum%10);
            }else {
                tmp.next = new ListNode(sum%10);
                tmp = tmp.next;
            }
            carry = sum/10;
            if(l1!=null){
                l1 = l1.next;
            }
            if(l2!=null){
                l2 = l2.next;
            }
        }
        if(carry>0){
            tmp.next = new ListNode(carry);
        }
        return head;
    }

    public List play(ListNode node){
        List<Integer> list = new ArrayList<>();
        while (node!=null){
            list.add(node.val);
            node = node.next;
        }
        return list;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode l1 =null,head1 = null;
        ListNode l2 =null,head2 = null;
        Random rand = new Random();
        int i_max = rand.nextInt(20)+1;
        int j_max = rand.nextInt(20)+1;
        for(int i = 0; i<i_max; i++) {
            if (l1 == null) {
                head1 = l1 = new ListNode(rand.nextInt(8) + 1);
            } else {
                head1.next = new ListNode(rand.nextInt(8) + 1);
                head1 = head1.next;
            }
        }
        for(int j = 0; j<j_max; j++) {
            if(l2==null){
                head2 = l2 = new ListNode(rand.nextInt(8)+1);
            }else {
                head2.next = new ListNode(rand.nextInt(8)+1);
                head2 = head2.next;
            }
        }
        System.out.println(solution.play(l1));
        System.out.println(solution.play(l2));
        System.out.println(solution.play(solution.addTwoNumbers(l1,l2)));
    }
}

测试结果

[1, 6, 3, 5, 3, 3, 1, 5, 6, 1, 3, 8, 7, 8, 7, 8]
[2, 4, 6, 4, 6, 3, 4, 4, 4, 4, 4, 8, 6, 1, 8]
[3, 0, 0, 0, 0, 7, 5, 9, 0, 6, 7, 6, 4, 0, 6, 9]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值