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还有长度,另一个已经结束的情况。

代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
14         
15           ListNode head = new ListNode(0);
16           ListNode tail = head;
17           int sum = 0;
18           int carry = 0;
19           
20           while(l1 != null || l2 != null){
21               if(l1 == null){
22                   sum = l2.val + carry;
23                   l2 = l2.next;
24               }
25               else if (l2 == null){
26                   sum = l1.val + carry;
27                   l1 = l1.next;
28               }
29               else{
30                   sum = l1.val + l2.val + carry;
31                   l1 = l1.next;
32                   l2 = l2.next;
33               }
34               
35               if(sum >= 10){
36                   carry = sum / 10;
37                   sum = sum % 10;
38               }
39               else{
40                   carry = 0;
41               }
42               
43               tail.next = new ListNode(sum);
44               tail = tail.next;
45           }
46           
47           if(carry != 0){
48               tail.next = new ListNode(carry);
49               tail = tail.next;
50           }
51           
52           return head.next;
53     }
54 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。