当前位置:网站首页>【Hot100】2. Add two numbers
【Hot100】2. Add two numbers
2022-06-28 16:18:00 【Wang Liuliu's it daily】
Medium question
subject :
Here are two for you Non empty The linked list of , Represents two nonnegative integers . Each of them is based on The reverse Stored in , And each node can only store a Numbers .
Please add up the two numbers , And returns a linked list representing sum in the same form .
You can assume that in addition to the numbers 0 outside , Neither of these numbers 0 start .
Answer key :
label : Linked list
Think of two linked lists as traversal of the same length , If a linked list is short, fill in at the end 0, such as 987 + 23 = 987 + 230 =128
Traverse two linked lists at the same time , Calculate their sum bit by bit , And with the carry value of the current position c a r r y carry carry Add up .
Specific simulation process :
We traverse two linked lists at the same time , Calculate their sum bit by bit , And add it to the carry value of the current position . To be specific , If the numbers in the corresponding positions of the current two linked lists are x , y x,y x,y, Carry value is c a r r y carry carry, Then he is x + y + c a r r y x+y+carry x+y+carry, The node value is ( x + y + c a r r y ) m o d 10 (x+y+carry) mod 10 (x+y+carry)mod10, The new carry value is x + y + c a r r y 10 \frac{x+y+carry}{10} 10x+y+carry.
If the two lists are all traversed , Carry value ==1, Then a node is appended to the new linked list , The node value is a carry value .
Tips : For the list problem , When the return result is the header node , Usually you need to initialize a Pre pointer pre, The next node of the pointer points to the real header node head.
Using a pre pointer Purpose The reason is that there is no available node value when the linked list is initialized , And the construction process of linked list needs pointer movement , This will result in the loss of the head pointer , Unable to return a result .
Be careful :
① Linked list must pass new ListNode( Node values ) Method to assign a value to a node
② To get the node value, use .val
③ Get the length corresponding to the two linked lists
④ Fill in zero at the end of the short linked list ( Because it's in reverse order )
⑤ Align and add considering carry , The current node value is after the remainder , The carry value is rounded to
⑥ The sum of two numbers is less than at most 20, therefore carry The maximum value of can only be 1
Code :
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
// Initialize carry value
int carry = 0;
while(l1 != null || l2 != null){
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
// Add a node after the pre node and assign a value
cur.next = new ListNode(sum);
// Move backward
cur = cur.next;
if(l1 != null){
l1 = l1.next;
}
if(l2 != null){
l2 = l2.next;
}
// When the linked list traversal ends , If there is a carry value, add a carry value after the linked list
if(carry == 1){
cur.next = new ListNode(carry);
}
}
// Returns the entire list
return pre.next;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Define a new join table pseudo pointer , Pointer to the head , Return results
ListNode prev = new ListNode(0);
// Define a carry pointer , Used to store when the sum of two numbers is greater than 10 When ,
int carry = 0;
// Define a movable pointer , Used to point to the location where the sum of two numbers is stored
ListNode cur = prev;
// When l1 It's not equal to null or l2 Not equal to empty time , Go into the cycle
while(l1!=null || l2!=null){
// If l1 It's not equal to null when , Take his value , be equal to null when , Just assign 0, Keep two linked lists with the same number of digits
int x= l1 !=null ? l1.val : 0;
// If l1 It's not equal to null when , Take his value , be equal to null when , Just assign 0, Keep two linked lists with the same number of digits
int y = l2 !=null ? l2.val : 0;
// The values of the two linked lists , Add additivity , And add the carry
int sum = x + y + carry;
// Calculate the progression
carry = sum / 10;
// Calculate the sum of two numbers , Exclude more than 10 Your request ( Greater than 10, Take the remainder )
sum = sum % 10;
// Assign the summation number to the node of the new linked list ,
// Note that at this time, you can't directly sum Assign a value to cur.next = sum. It will be reported at this time , Type mismatch .
// So we need to create a new node at this time , Assign values to nodes
cur.next = new ListNode(sum);
// Move the node of the new linked list back
cur = cur.next;
// When linked list l1 It's not equal to null When , take l1 Move the node back
if(l1 !=null){
l1 = l1.next;
}
// When linked list l2 It's not equal to null When , take l2 Move the node back
if(l2 !=null){
l2 = l2.next;
}
}
// If the last two numbers , When there are carry digits when adding , Just carry the number , Give a new node to the linked list .
// The sum of two numbers is less than at most 20, So the maximum value of can only be 1
if(carry == 1){
cur.next = new ListNode(carry);
}
// Return the head node of the linked list
return prev.next;
}
}
边栏推荐
- 你好,现在网上炒股开户买股票安全吗?
- Visual Studio 2010 configuring and using qt5.6.3
- 大神详解开源 BUFF 增益攻略丨直播讲座
- A little hesitant in the morning
- LDD 知识整理
- 【Redis】2021/01/31 Redis的简单归纳 No.01
- QT create 5.0.3 configuring qt4.8.7
- 如何查询数据库中一个表中的所有数据呢?
- Soliciting articles and contributions - building a blog environment with a lightweight application server
- 软件测试员的悲哀竟是...自己的技术能力不能满足大厂要求?
猜你喜欢
![[high concurrency foundation] hidden dangers and solutions of MySQL concurrency under different transaction isolation levels](/img/35/63c9793ec7bc1c90c759504e84dc96.png)
[high concurrency foundation] hidden dangers and solutions of MySQL concurrency under different transaction isolation levels

【初学者必看】vlc实现的rtsp服务器及转储H264文件

今天睡眠质量记录80分

What is the maximum number of concurrent TCP connections for a server? 65535?

Big God explains open source buff gain strategy live lecture
![[Spock] process non ASCII characters in an identifier](/img/ab/d2cd6802d1e2af009da077ae82bdf8.png)
[Spock] process non ASCII characters in an identifier

5分钟的时间制作一个反弹球游戏

The world has embraced Web3.0 one after another, and many countries have clearly begun to seize the initiative

Briefly introduce the conversion between tensorflow and pytorch (mainly tensorflow to pytorch)

Azure Kinect Microsoft camera unity development summary
随机推荐
Redmibook Pro 14 enhanced version cannot open delta software drastudio_ v1.00.07.52
Steps to be taken for successful migration to the cloud
[MySQL] official website document learning query statement SQL precautions
Kiss in the metauniverse! CMU launched VR head display plug-in, reproducing the vivid touch of lips
【Hot100】3. 无重复字符的最长子串
A new 25K byte from the Department showed me what the ceiling is
leetcode:22. 括号生成
知道这几个命令让你掌握Shell自带工具
Etcd visualization tool: an introduction to kstone (I)
媒体数据处理V2版本(VPC)图像缩放内容解析
Among US private server setup
Convolutional neural networks for machine learning -- an introduction to CNN
【力扣】35. 搜索插入位置
PostgreSQL enables grouping statistics by year, month, day, week, hour, minute and second
【初学者必看】vlc实现的rtsp服务器及转储H264文件
A 24-year-old bald programmer teaches you how to continuously integrate and deliver microservice delivery. You can't learn how to cut me off
你好,现在网上炒股开户买股票安全吗?
Naacl 2022 | distillation of machinetranslation SOTA model
Slim gain (sgain) introduction and code implementation -- missing data filling based on generated countermeasure network
5分钟的时间制作一个反弹球游戏