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 
发布了85 篇原创文章 · 获赞 72 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/a1786742005/article/details/104479257