Java [leetcode 2] Add Two Numbers
问题描述:
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
解题思路:
设立一个头ListNode和尾ListNode,两个List分别从头开始,两两相加并且设立进位carry,如果相加超过10则carry为1,否则为零。同时需要考虑一个List还有长度,另一个已经结束的情况。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode tail = head;
int sum = 0;
int carry = 0;
while(l1 != null || l2 != null){
if(l1 == null){
sum = l2.val + carry;
l2 = l2.next;
}
else if (l2 == null){
sum = l1.val + carry;
l1 = l1.next;
}
else{
sum = l1.val + l2.val + carry;
l1 = l1.next;
l2 = l2.next;
}
if(sum >= 10){
carry = sum / 10;
sum = sum % 10;
}
else{
carry = 0;
}
tail.next = new ListNode(sum);
tail = tail.next;
}
if(carry != 0){
tail.next = new ListNode(carry);
tail = tail.next;
}
return head.next;
}
}
浙公网安备 33010602011771号