LeetCode2--两数相加

LeetCode2–两数相加

一、问题描述:

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字0之外,这两个数字不会以0开头。
示例:

输入:(2->4->3)+(5>6>4)
输出:7->0->8
原因:342+465=807

二、代码实现:

 public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode(0);//用来存储
        ListNode listNode2 = listNode;
        int z = 0 ;
        while (l1 != null || l2 != null){
            int x ;
            int y ;
            x = l1 != null ? l1.val : 0; //如果为空的话 用0赋值
            y = l2 != null ? l2.val : 0;
            listNode2.next = new ListNode((x + y + z) % 10);//计算取余
            listNode2 = listNode2.next;
            z = (x + y + z) >= 10 ?1:0;//这个是给下一位的进位
            if (l1 != null)l1 = l1.next ; //下一位
            if (l2 != null)l2 = l2.next ;
        }
        if (z > 0 ){//如果最高位也有进位,再申请一个结点
            listNode2.next = new ListNode(z);
        }
        return listNode.next ;
    }

三、完整代码测试(IDEA2019开发环境)

package LeetCode2;

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode(0);//用来存储
        ListNode listNode2 = listNode;
        int z = 0 ;
        while (l1 != null || l2 != null){
            int x ;
            int y ;
            x = l1 != null ? l1.val : 0; //如果为空的话 用0赋值
            y = l2 != null ? l2.val : 0;
            listNode2.next = new ListNode((x + y + z) % 10);//计算取余
            listNode2 = listNode2.next;
            z = (x + y + z) >= 10 ?1:0;//这个是给下一位的进位
            if (l1 != null)l1 = l1.next ; //下一位
            if (l2 != null)l2 = l2.next ;
        }
        if (z > 0 ){//如果最高位也有进位,再申请一个结点
            listNode2.next = new ListNode(z);
        }
        return listNode.next ;
    }
    public static void main(String[] age){
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(4);
        ListNode listNode3 = new ListNode(3);
        listNode2.next = listNode3;
        listNode1.next = listNode2;


        ListNode listNode4 = new ListNode(5);
        ListNode listNode5 = new ListNode(6);
        ListNode listNode6 = new ListNode(4);
        listNode5.next = listNode6;
        listNode4.next = listNode5;


        ListNode listNode = addTwoNumbers(listNode1, listNode4);
        while (listNode != null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}

在这里插入图片描述

posted @ 2020-06-14 11:19  别团等shy哥发育  阅读(18)  评论(0)    收藏  举报