2. Add Two Numbers
2018-05-23 本文已影响0人
与你若只如初见v
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode t1 = l1, t2 = l2, r = new ListNode(0);
ListNode now = r;
boolean f = false;
while(t1 != null || t2 != null){
int sum = 0;
sum += (t1 != null) ? t1.val : 0;
sum += (t2 != null) ? t2.val : 0;
if(f == true){
sum += 1;
f = false;
}
if(sum / 10 != 0){f = true;}
ListNode node = new ListNode(sum % 10);
now.next = node;
now = node;
if(t1 != null){t1 = t1.next;}
if(t2 != null){t2 = t2.next;}
}
if(f == true){
ListNode node = new ListNode(1);
now.next = node;
}
return r.next;
}
}