标签:span ext result 循环 除了 public 两数相加 isa title
题目
解题
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { //若其中一个链表是0,返回另外一个 if (l1.val == 0 && l1.next == null) return l2; if (l2.val == 0 && l2.next == null) return l1; //个位相加 var sum = l1.val + l2.val; var isAddOne = sum > 9; var result = new ListNode(isAddOne ? sum % 10 : sum); var current = result; //循环相加 while (true) { l1 = l1?.next; l2 = l2?.next; if (l1 == null && l2 == null) break; sum = (l1?.val ?? 0) + (l2?.val ?? 0) + (isAddOne ? 1 : 0); //考虑进位 isAddOne = sum > 9; current.next = new ListNode(isAddOne ? sum % 10 : sum); current = current.next; } //最高位若有进位 if (isAddOne) { current.next = new ListNode(1); } return result; }
来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/add-two-numbers
标签:span ext result 循环 除了 public 两数相加 isa title
原文地址:https://www.cnblogs.com/WilsonPan/p/11681720.html