leetcode刷题31

今天刷的题是LeetCode第2题,两数相加,现在来做这个题还是很简单的

首先想到的是,吧两个数都提取出来,然后相加,再生成新的链表,但是这个有个问题,就是数据有可能超过int类型的最大数。代码如下:

public static ListNode solution(ListNode l1,ListNode l2){
        //这种做法是不正确的,因为输入的字符串有可能超过int的最大范围
        ListNode head=new ListNode(0);
        ListNode p=head;
        StringBuilder stringBuilder=new StringBuilder();
        while (l1!=null){
            stringBuilder.insert(0,l1.val);
            l1=l1.next;
        }
        StringBuilder stringBuilder2=new StringBuilder();
        while (l2!=null){
            stringBuilder2.insert(0,l2.val);
            l2=l2.next;
        }
        int sum=Integer.parseInt(stringBuilder.toString())+Integer.parseInt(stringBuilder2.toString());
        List<Integer> list=new ArrayList<>();
        while (sum!=0){
            list.add(sum%10);
            sum=sum/10;
        }
        for (int i = 0; i <list.size() ; i++) {
            ListNode listNode=new ListNode(list.get(i));
            p.next=listNode;
            p=listNode;
        }
        return head.next;
    }

然后,因为数据是从低位到高位存储的嘛,因此,可以模拟数据相加的过程,直接相加即可。这时候需要注意的一点就是,需要一个全局的数,来保证数据是否需要进位,并且最终需要进行判断,如果所有数相加,最终有进位,那么还需要生成新的链表节点

public static ListNode solution2(ListNode l1,ListNode l2){
        ListNode head=new ListNode(0);
        ListNode p=head;
        int pre=0;
        while (l1!=null && l2!=null){
            int num1=l1.val;
            int num2=l2.val;
            l1=l1.next;
            l2=l2.next;
            int sum=num1+num2+pre;
            ListNode newnode=new ListNode(sum%10);
            pre=sum/10;
            p.next=newnode;
            p=newnode;
        }
        ListNode others=new ListNode(0);
        if (l1!=null){
            others.next=l1;
        }else if (l2!=null){
            others.next=l2;
        }
        others=others.next;
        while (others!=null){
            int num=others.val;
            int sum=num+pre;
            ListNode newnode=new ListNode(sum%10);
            pre=sum/10;
            p.next=newnode;
            p=newnode;
            others=others.next;
        }
        if (pre!=0){
            ListNode newnode=new ListNode(pre);
            p.next=newnode;
        }
        return head.next;
    }
原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11517012.html