内容简介:给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解题思路:
- 链表遍历,最后结果返回头
- 两个链表不一定等长
- 考虑进位
Java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode resultHeader = new ListNode(0);
ListNode next1 = l1, next2 = l2, sumNext = resultHeader;
int up, sum;
boolean doSum = true;
while (doSum) {
if (next1 == null && next2 != null) {
sum = sumNext.val + next2.val;
next2 = next2.next;
} else if (next1 != null && next2 == null) {
sum = sumNext.val + next1.val;
next1 = next1.next;
} else {
sum = next1.val + next2.val + sumNext.val;
next1 = next1.next;
next2 = next2.next;
}
up = sum / 10;
sumNext.val = up > 0 ? sum - 10 : sum;
if ((doSum = next1 != null || next2 != null) || up > 0) {
sumNext.next = new ListNode(up);
sumNext = sumNext.next;
}
}
return resultHeader;
}
Golang实现
这道题 Go 的执行速度虽然超过了97%了Go的提交,但是居然比 java 慢!
提交结果
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
header := ListNode{0, nil}
next1, next2, sumNext := l1, l2, &header
up, sum := 0, 0
doSum := true
for doSum {
if next1 == nil && next2 != nil {
sum = sumNext.Val + next2.Val
next2 = next2.Next
} else if next2 == nil && next1 != nil {
sum = sumNext.Val + next1.Val
next1 = next1.Next
} else {
sum = sumNext.Val + next1.Val + next2.Val
next2 = next2.Next
next1 = next1.Next
}
up = sum / 10
if up > 0 {
sumNext.Val = sum - 10
} else {
sumNext.Val = sum
}
doSum = next1 != nil || next2 != nil
if doSum || up > 0 {
sumNext.Next = &ListNode{up, nil}
sumNext = sumNext.Next
}
}
return &header
}
来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- flex actionScript时间处理相加返回相加后的date
- LeetCode:两数相加
- 算法 链表相加问题
- 【算法】2. 两数相加
- LeetCode——两数相加
- LeetCode (2):两数相加
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming Amazon Web Services
James Murty / O'Reilly Media / 2008-3-25 / USD 49.99
Building on the success of its storefront and fulfillment services, Amazon now allows businesses to "rent" computing power, data storage and bandwidth on its vast network platform. This book demonstra......一起来看看 《Programming Amazon Web Services》 这本书的介绍吧!