LeetCode 445. Add Two Numbers II
来源:互联网 发布:我要请运营淘宝的 编辑:程序博客网 时间:2024/06/05 23:03
原题网址:https://leetcode.com/problems/add-two-numbers-ii/
You are given two linked lists representing two non-negative numbers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7
方法:如果不能反转原链表的话,可以反转结果链表。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { private int length(ListNode node) { if (node == null) return 0; return 1 + length(node.next); } private ListNode reverse(ListNode node) { if (node == null) return null; if (node.next == null) return node; ListNode prev = node; ListNode curr = node.next; prev.next = null; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int len1 = length(l1); int len2 = length(l2); int len = Math.max(len1, len2); ListNode start = new ListNode(0); ListNode node = start; for(int i = 0; i < len; i++) { node.next = new ListNode(0); node = node.next; if (i + len1 >= len) { node.val += l1.val; l1 = l1.next; } if (i + len2 >= len) { node.val += l2.val; l2 = l2.next; } } start.next = reverse(start.next); node = start; int carry = 0; while (node.next != null) { node = node.next; node.val += carry; carry = node.val / 10; node.val %= 10; } if (carry != 0) { node.next = new ListNode(carry); } start.next = reverse(start.next); return start.next; }}
0 0
- LeetCode 445. Add Two Numbers II
- leetcode-445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- [LeetCode]445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- 【LeetCode】 445. Add Two Numbers II
- LeetCode笔记:445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- 【Leetcode】445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- Leetcode-445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- [LeetCode] 445. Add Two Numbers II
- [LeetCode]445. Add Two Numbers II
- 设计模式实用案例之单例模式
- 电脑ip变动导致Android Studio中 SVN无法上传更新项目的解决方法
- 2793: [Poi2012]Vouchers
- Window.open()方法参数详解
- C#序列化与反序列化
- LeetCode 445. Add Two Numbers II
- 导入library
- SystemUI状态条下拉视图显示过程
- Android屏幕视频技巧
- mysql如何提高其查询速度的方法
- ANDROID断点调试
- JDBC连接数据库步骤
- leetcode24:Swap Nodes in Pairs
- MySQL 设置远程访问数据库