当前位置:网站首页>2. 两数相加
2. 两数相加
2022-08-03 05:09:00 【破烂摆烂人】


方法一:初等数学


public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null/*新建链表的头尾指针*/;
int carry = 0/*上一位的进位*/;
/*逐步相加:初等数学*/
while(l1 != null && l2 != null){
int sum = l1.val + l2.val + carry;
if(head == null){
head = tail = new ListNode(sum%10);
} else {
tail.next = new ListNode(sum%10);
tail = tail.next;
}
carry = sum/10;
l1 = l1.next;
l2 = l2.next;
}
/*处理剩余部分(注意进位)*/
while(l1 != null){
int sum = l1.val+carry;
tail.next = new ListNode(sum%10);
tail = tail.next;
l1 = l1.next;
carry = sum/10;
}
while(l2 != null){
int sum = l2.val+carry;
tail.next = new ListNode(sum%10);
tail= tail.next;
l2 = l2.next;
carry = sum/10;
}
/*最后有可能是进位*/
if(carry > 0){
tail.next = new ListNode(carry);
tail= tail.next;
}
return head;
}

边栏推荐
- Secondary development of WinForm controls
- Interface Test Framework Practice (4) | Get Schema Assertion
- MOSN 反向通道详解
- MySQL 入门:Case 语句很好用
- 社交电商:流量红利已尽,裂变营销是最低成本的获客之道
- Get the Ip tool class
- Alienware上线首个数字时装AR试穿体验
- UV decomposition of biotin - PEG2 - azide | CAS: 1192802-98-4 biotin connectors
- 3. 无重复字符的最长子串
- DFS's complement to pruning
猜你喜欢

常见荧光染料修饰多种基团及其激发和发射波长数据一览数据

接口管理工具YApi怎么用?颜值高、易管理、超好用

【生物素叠氮化物|cas:908007-17-0】价格_厂家

shell script loop statement

接口和抽象

【Harmony OS】【ArkUI】ets开发 图形与动画绘制

荧光标记多肽FITC/AMC/FAM/Rhodamine/TAMRA/Cy3/Cy5/Cy7-Peptide

链动2+1模式简单,奖励结构丰厚,自主裂变?

WinForm的控件二次开发

安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
随机推荐
接口测试框架实战(四)| 搞定 Schema 断言
Alienware上线首个数字时装AR试穿体验
OSI的分层特点、传输过程与三次握手、四次挥手、tcp与udp包头的描述
阿里云对象存储oss私有桶生成链接
rosbag工具plotjuggler无法打开rosbag的问题
Secondary development of WinForm controls
常见亲脂性细胞膜染料DiO, Dil, DiR, Did光谱图和实验操作流程
接口测试如何准备测试数据
How to prepare for the test interface test data
索引创建、删除与使用
安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
2022/08/02 Study Notes (day22) Multithreading
【Biotin Azide|cas:908007-17-0】Price_Manufacturer
Jmeter 模拟多用户登录的两种方法
接口测试 Mock 实战(二) | 结合 jq 完成批量化的手工 Mock
JS底层手写
数字化时代,企业如何建立自身的云平台与商业模式的选择?
Common lipophilic cell membrane dyes DiO, Dil, DiR, Did spectrograms and experimental procedures
DFS's complement to pruning
软件开发的最大的区别是什么?