LeetCode算法 -- 两数相加(第1题)

一、题目介绍

在这里插入图片描述

二、求解代码

2.1 定义一个单链表节点

package question1;

/**
 * @description: 定义一个单链表节点
 * @author: hyr
 * @time: 2020/2/23 20:50
 */
public class ListNode {
    int val;
    ListNode next;

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

    @Override
    public String toString() {
        return String.valueOf(val);
    }
}

2.2 编写解题方法类

package question1;

/**
 * @description: 编写解题方法
 * @author: hyr
 * @time: 2020/2/23 20:52
 */
class Solution {
    /*
        思路就是从低位数开始两数相加,这里主要进位这个问题。
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(0);
        ListNode cursor = root;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            int sumVal = l1Val + l2Val + carry;
            carry = sumVal / 10;

            ListNode sumNode = new ListNode(sumVal % 10);
            cursor.next = sumNode;
            cursor = sumNode;

            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        return root.next;
    }
}

2.3 测试类

package question1;

/**
 * @description: 测试结果
 * @author: hyr
 * @time: 2020/2/23 20:55
 */
public class SolutionTest {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(4);
        ListNode listNode3 = new ListNode(3);

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

        listNode1.next = listNode2;
        listNode2.next = listNode3;

        listNode4.next = listNode5;
        listNode5.next = listNode6;

        System.out.println("第一个链表为:");
        show(listNode1);
        System.out.println();

        System.out.println("第二个链表为:");
        show(listNode4);

        System.out.println();
        ListNode result = null;
        result = Solution.addTwoNumbers(listNode1, listNode4);

        System.out.println("结果为:");
        show(result);
    }

    public static void show(ListNode node){
        while (node != null){
            System.out.print(node + " ");
            node = node.next;
        }
    }
}

2.4 测试结果

第一个链表为:
2 4 3 
第二个链表为:
5 6 4 
结果为:
7 0 8 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值