博客
关于我
LeetCode-Add Two Numbers
阅读量:800 次
发布时间:2023-01-31

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

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.

要注意的是两个链表可能不一样长度。

还有不能还原成数字,因为不知道链表的长度,可能链表的长度很大,超过了int的范围,或者超过了double的范围。

只能一位一位的变化。

代码是抄的LeetCode的代码。

自己没有写出来。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2){        ListNode dummyHead = new ListNode(0);        ListNode p = l1, q = l2, curr = dummyHead;        int carry = 0;        while (p != null || q != null) {            int x = (p != null) ? p.val : 0;            int y = (q != null) ? q.val : 0;            int sum = carry + x + y;            carry = sum / 10;            curr.next = new ListNode(sum % 10);            curr = curr.next;            if (p != null) p = p.next;            if (q != null) q = q.next;        }        if (carry > 0) {            curr.next = new ListNode(carry);        }        return dummyHead.next;    }

 

转载于:https://www.cnblogs.com/LoganChen/p/8783943.html

你可能感兴趣的文章
NEW DATE()之参数传递
查看>>
New Relic——手机应用app开发达人的福利立即就到啦!
查看>>
new 一个button 然后dispose,最后这个button是null吗???
查看>>
next项目部署到服务器pm2进程守护
查看>>
nexus上传jar
查看>>
Nexus指南中的更新强调集成和透明度的重要性
查看>>
Nexus指南已经发布
查看>>
Nexus(1):Nexus的安装与配置
查看>>
NFinal学习笔记 02—NFinalBuild
查看>>
NFS
查看>>
NFS Server及Client配置与挂载详解
查看>>
NFS 服务配置篇
查看>>
NFS共享文件系统搭建
查看>>
nfs复习
查看>>
NFS安装配置
查看>>
NFS服务器配置-服务启动与停止
查看>>
NFS的安装以及windows/linux挂载linux网络文件系统NFS
查看>>
NFS的常用挂载参数
查看>>
NFS网络文件系统
查看>>
NFS远程目录挂载
查看>>