【leetcode刷题笔记】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


 

题解:模拟即可。用carries保存进位,当l1和l2一方为空的时候,余下不为空的链表要单独处理。当l1和l2都为空的时候,如果carries不为空,那么要再单独申请一个链表存放carries,代码如下:

 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         if(l1 == null && l2 == null)

15             return null;

16         

17         ListNode kepeler = new ListNode(0);

18         ListNode head = kepeler;

19         int carries = 0;

20         

21         while(l1 != null && l2 != null){

22             int sum = carries + l1.val + l2.val;

23             carries = sum/10;

24             kepeler.next = new ListNode(sum%10);

25             kepeler = kepeler.next;

26             l1 = l1.next;

27             l2 = l2.next;

28         }

29         

30         while(l1 != null){

31             int sum = carries + l1.val;

32             carries = sum/10;

33             kepeler.next = new ListNode(sum%10);

34             l1 = l1.next;

35             kepeler = kepeler.next;

36         }

37         

38         while(l2 != null){

39             int sum = carries + l2.val;

40             carries = sum/10;

41             kepeler.next = new ListNode(sum%10);

42             l2 = l2.next;

43             kepeler = kepeler.next;

44         }

45         

46         if(carries != 0)

47             kepeler.next = new ListNode(carries);

48         

49         return head.next;

50     }

51 }

你可能感兴趣的:(LeetCode)