首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode2--两数相加

LeetCode2--两数相加

作者头像
别团等shy哥发育
发布于 2023-02-27 10:29:26
发布于 2023-02-27 10:29:26
4020
举报

LeetCode2–两数相加

一、问题描述:

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

代码语言:javascript
复制
输入:(2->4->3)+(5>6>4)
输出:7—->0->8
原因:342+465=807

二、代码实现:

代码语言:javascript
复制
 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开发环境)

代码语言:javascript
复制
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;
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • LeetCode2–两数相加
  • 一、问题描述:
  • 二、代码实现:
  • 三、完整代码测试(IDEA2019开发环境)
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档