力扣(LeetCode)试题--两数相加
发布日期:2021-06-29 15:51:53 浏览次数:2 分类:技术文章

本文共 2140 字,大约阅读时间需要 7 分钟。

两数相加( Add Two Numbers)

题目描述

中文描述

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

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

English

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8Explanation: 342 + 465 = 807

难度:中等

解题思路

两个数相加时,直接从链表的头开始对齐相加,结果保存在一个新的链表中,最后再遍历结果链表,将值大于10的节点进行进位

代码实现

public class ListNode {
int val; public ListNode next; public ListNode(int x) {
val = x; }}public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1=l1; ListNode head2=l2; ListNode result=null; ListNode reHead=result; if (head1!=null && head2!=null){
result=new ListNode(head1.val+head2.val); head1=head1.next; head2=head2.next; reHead=result; } while (head1!=null && head2!=null){
reHead.next=new ListNode(head1.val+head2.val); head1=head1.next; head2=head2.next; reHead=reHead.next; } while (head1!=null){
reHead.next=new ListNode(head1.val); head1=head1.next; reHead=reHead.next; } while (head2!=null){
reHead.next=new ListNode(head2.val); head2=head2.next; reHead=reHead.next; } reHead=result; while (reHead!=null){
if (reHead.val>=10){
if (reHead.next!=null){
reHead.next.val+=reHead.val/10; }else {
reHead.next=new ListNode(reHead.val/10); } reHead.val=reHead.val%10; } reHead=reHead.next; } return result; }}

测试结果

测试结果

转载地址:https://console.blog.csdn.net/article/details/105756997 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:程序员如何优雅地统计自己写bug时间分布
下一篇:力扣(LeetCode)试题--两数之和

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月14日 18时51分08秒