您的位置:首页 > 其它

Add Two Numbers I & II

2016-07-16 00:11 323 查看

Add Two Numbers I

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in
reverse
order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given
7->1->6 + 5->9->2
. That is,
617 + 295
.

Return
2->1->9
. That is
912
.

Given
3->1->5
and
5->9->2
, return
8->0->8
.

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;

int value1 = 0, value2 = 0, carry = 0, sum = 0;
ListNode head = new ListNode(0);
ListNode current = head;

while (l1 != null || l2 != null || carry == 1) {
value1 = (l1 == null ? 0 : l1.val);
value2 = (l2 == null ? 0 : l2.val);
sum = value1 + value2 + carry;

current.next = new ListNode(sum % 10);
current = current.next;

carry = sum / 10;
l1 = (l1 == null) ? null : l1.next;
l2 = (l2 == null) ? null : l2.next;
}
return head.next;
}
}


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

分析: reverse 之后再相加,然后再reverse result linkedlist

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;

l1 = reverse(l1);
l2 = reverse(l2);

return reverse(helper(l1, l2));
}

public ListNode reverse(ListNode head) {
if (head == null || head.next == null) return head;

ListNode pre = null;
ListNode current = head;
ListNode next = null;

while (current != null) {
next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}

public ListNode helper(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;

int value1 = 0, value2 = 0, carry = 0, sum = 0;
ListNode head = new ListNode(0);
ListNode current = head;

while (l1 != null || l2 != null || carry == 1) {
value1 = (l1 == null ? 0 : l1.val);
value2 = (l2 == null ? 0 : l2.val);
sum = value1 + value2 + carry;

current.next = new ListNode(sum % 10);
current = current.next;

carry = sum / 10;
l1 = (l1 == null) ? null : l1.next;
l2 = (l2 == null) ? null : l2.next;
}
return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: