当前位置:网站首页>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;
}

边栏推荐
- Talking about GIS Data (5) - Geographic Coordinate System
- unity2D横板游戏教程6-敌人AI以及受击动画
- Technology Sharing | How to do assertion verification for xml format in interface automation testing?
- [Fine talk] Using native js to implement todolist
- Interface test framework combat (1) | Requests and interface request construction
- 内部类、static关键字、final
- C#异步和多线程
- idea使用@Autowired注解爆红原因及解决方法
- [Harmony OS] [ARK UI] ETS context basic operations
- DDL操作数据库、表、列
猜你喜欢

内部类、static关键字、final

接口测试框架实战 | 流程封装与基于加密接口的测试用例设计
![[Harmony OS] [ArkUI] ets development graphics and animation drawing](/img/36/f4c91f794b1321f11a24505d1617fb.png)
[Harmony OS] [ArkUI] ets development graphics and animation drawing

修饰生物素DIAZO-生物素-PEG3-DBCO|重氮-生物素-三聚乙二醇-二苯基环辛炔

Fluorescent marker peptides FITC/AMC/FAM/Rhodamine TAMRA/Cy3 / Cy5 / Cy7 - Peptide

【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接

Where is the value of testers

FileZilla 搭建ftp服务器

MOSN 反向通道详解

typescript39-class类的可见修饰符
随机推荐
mysql 创建索引的三种方式
Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
WebSocket的实际应用
Interface Test Framework Practice (4) | Get Schema Assertion
typescript47-函数之间的类型兼容性
接口测试框架实战(三)| JSON 请求与响应断言
接口管理工具YApi怎么用?颜值高、易管理、超好用
[Developers must see] [push kit] Collection of typical problems of push service service 2
安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
接口测试框架实战 | 流程封装与基于加密接口的测试用例设计
获取Ip工具类
MySQL 出现 The table is full 的解决方法
unity2D横板游戏教程6-敌人AI以及受击动画
表的创建、修改与删除
[Fine talk] Using native js to implement todolist
PotPlayer实现上班摸鱼电视自由
shell脚本循环语句
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
Talking about GIS Data (6) - Projected Coordinate System
在树莓派上搭建属于自己的网页(2)