首页 > 代码库 > LeetCode 2. Add Two Numbers
LeetCode 2. Add Two Numbers
public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } public class Solution { public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { ListNode lnResult = new ListNode(0); ListNode currentNode = lnResult; ListNode pre = null; int carry = 0; while (l1 != null && l2 != null) { currentNode.val = (l1.val + l2.val + carry) % 10; carry = (l1.val + l2.val + carry) / 10; pre = currentNode; currentNode = new ListNode(0); pre.next = currentNode; l1 = l1.next; l2 = l2.next; } currentNode = AddWithCarry(l1, l2, carry); pre.next = currentNode; return lnResult; } public ListNode AddWithCarry(ListNode l1, ListNode l2, int carry) { ListNode cur = null; if (l1 == null && l2 == null) { if (carry != 0) { cur = new ListNode(0); cur.val = carry; return cur; } return null; } if (l1 == null) { return AddWithCarry(l2, l1, carry); } ListNode result = new ListNode(0); cur = result; ListNode pre = null; while (l1 != null) { cur.val = (l1.val + carry) % 10; carry = (l1.val + carry) / 10; pre = cur; cur = new ListNode(carry); pre.next = cur; l1 = l1.next; } if (pre.next.val == 0) { pre.next = null; } return result; } }
LeetCode 2. Add Two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。