首页 > 其他分享 >#yyds干货盘点# LeetCode面试题:两数相加

#yyds干货盘点# LeetCode面试题:两数相加

时间:2023-02-02 18:32:03浏览次数:48  
标签:yyds 面试题 ListNode tail l2 l1 carry null LeetCode

1.简述:

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

 

示例 1:

输入:l1 = [2,4,3], l2 = [5,6,4]

输出:[7,0,8]

解释:342 + 465 = 807.

示例 2:

输入:l1 = [0], l2 = [0]

输出:[0]

示例 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]

输出:[8,9,9,9,0,0,0,1]

2.代码实现:

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;
int carry = 0;
while (l1 != null || l2 != null) {
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
if (head == null) {
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
tail.next = new ListNode(carry);
}
return head;
}
}

标签:yyds,面试题,ListNode,tail,l2,l1,carry,null,LeetCode
From: https://blog.51cto.com/u_15488507/6033836

相关文章

  • #yyds干货盘点# LeetCode程序员面试金典:幂集
    题目:幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。说明:解集不能包含重复的子集。示例:输入:nums=[1,2,3]输出:[ [3], [1], [2], [1,2,3],......
  • LeetCode.150 逆波兰表达式求值
    1.题目给你一个字符串数组 ​​tokens​​​ ,表示一个根据 ​​逆波兰表示法​​ 表示的算术表达式。请你计算该表达式。返回一个表示表达式值的整数。2.代码classSolu......
  • [LeetCode]Minimum Path Sum
    QuestionGivenamxngridfilledwithnon-negativenumbers,findapathfromtoplefttobottomrightwhichminimizesthesumofallnumbersalongitspath.N......
  • [LeetCode]Unique Paths
    QuestionArobotislocatedatthetop-leftcornerofamxngrid(marked‘Start’inthediagrambelow).Therobotcanonlymoveeitherdownorrightatany......
  • [LeetCode]Permutation Sequence
    QuestionTheset[1,2,3,…,n]containsatotalofn!uniquepermutations.Bylistingandlabelingallofthepermutationsinorder,Wegetthefollowingsequen......
  • [LeetCode]Length of Last Word
    QuestionGivenastringsconsistsofupper/lower-casealphabetsandemptyspacecharacters​​​''​​,returnthelengthoflastwordinthestring.Ifthe......
  • [LeetCode]Insert Interval
    QuestionGivenasetofnon-overlappingintervals,insertanewintervalintotheintervals(mergeifnecessary).Youmayassumethattheintervalswereinitial......
  • [LeetCode]Merge Intervals
    Question本题难度Hard。排序+双指针【复杂度】时间O(Nlog(N))空间O(N)【思路】先按照每个元素的​​​start​​​从小到大进行排序。然后利用双指针法,设置区间​​......
  • [LeetCode]Maximum Subarray
    QuestionFindthecontiguoussubarraywithinanarray(containingatleastonenumber)whichhasthelargestsum.Forexample,giventhearray[-2,1,-3,4,-1,2,1......
  • [LeetCode]Spiral Matrix
    QuestionGivenamatrixofmxnelements(mrows,ncolumns),returnallelementsofthematrixinspiralorder.Forexample,Giventhefollowingmatrix:[[1......