Add Two Numbers
2011-12-23 10:12
190 查看
First post here, : )
Problem
Add Two Numbers from http://www.leetcode.com/onlinejudge
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
This problem is easy, it 's a practice for traversing the list by using ListNode class the problem given.
1: go through two list
2:combine those two list(need ti be careful for handling Carry digit and one number is longer than other )
3:print answer
Problem
Add Two Numbers from http://www.leetcode.com/onlinejudge
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
This problem is easy, it 's a practice for traversing the list by using ListNode class the problem given.
1: go through two list
2:combine those two list(need ti be careful for handling Carry digit and one number is longer than other )
3:print answer
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1), p = head; ListNode A = l1; ListNode B = l2; int jin = 0; while ((A != null || B != null) || jin > 0) { int x = 0; if (A == null && B == null) { ListNode tmp = new ListNode(jin); p.next = tmp; p = tmp; break; } if (A == null && B != null) { x = B.val + jin; jin = x / 10; x = x % 10; ListNode tmp = new ListNode(x); p.next = tmp; p = tmp; B = B.next; continue; } if (A != null && B == null) { x = A.val + jin; jin = x / 10; x = x % 10; ListNode tmp = new ListNode(x); p.next = tmp; p = tmp; A = A.next; continue; } x = A.val + B.val + jin; jin = x / 10; x = x % 10; ListNode tmp = new ListNode(x); p.next = tmp; p = tmp; A = A.next; B = B.next; } return head.next; } }
相关文章推荐
- Add Two Numbers
- Add Two Numbers
- leetcode 2. Add Two Numbers
- [LeetCode]Add Two Numbers
- 【leetcode】 Add Two Numbers
- LeetCode-Add Two Numbers II
- (LeetCode)算法题目——Add Two Numbers
- Leetcode解题-链表(2.2.1)AddTwoNumbers
- LeetCode - Add Two Numbers - Frequent
- leetcode02-Add Two Numbers之beats98.68%Java版本号
- #2 Add Two Numbers (链表作加法)
- LeetCode OJ--Add Two Numbers
- lintcode-easy-Add two numbers
- Add Two Numbers
- Add Two Numbers 链表相加
- Add Two Numbers
- Add Two Numbers
- Add Two Numbers
- LeetCode 002-Add Two Numbers
- LeetCode题解--2-Add Two Numbers