Add Two Numbers
- Total Accepted: 160702
- Total Submissions: 664770
- Difficulty: Medium
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
本题的思路其实很简单,两个链表的结构都是从低位到高位的顺序,税后要求返回的链表也是这样的结构。所以我们只需要依次循环两个链表,将对应位的数相加,并判断是否有进位,有进位则将进位累加到下一位即可。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Num2 { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 if(l1 == null){ 12 return l2 ; 13 } 14 if(l2 == null){ 15 return l1 ; 16 } 17 int nextBit = (l1.val + l2.val)/10 ; 18 int curBit = (l1.val + l2.val)%10 ; 19 ListNode head = new ListNode(curBit) ; 20 ListNode temp = head ; 21 l1 = l1.next ; 22 l2 = l2.next ; 23 //当l1、l2对应位均存在时,进行计算 24 while(l1 != null && l2 != null){ 25 curBit = (l1.val + l2.val + nextBit) % 10 ; 26 nextBit = (l1.val + l2.val + nextBit)/10 ; 27 ListNode node = new ListNode(curBit) ; 28 temp.next = node ; 29 temp = temp.next ; 30 l1 = l1.next ; 31 l2 = l2.next ; 32 } 33 //判断l1是否结束,没有结束继续 34 while(l1 != null){ 35 curBit = (l1.val + nextBit) % 10 ; 36 nextBit = (l1.val + nextBit)/10 ; 37 ListNode node = new ListNode(curBit) ; 38 temp.next = node ; 39 temp = temp.next ; 40 l1 = l1.next ; 41 } 42 //判断l2是否结束,没有结束继续 43 while(l2 != null){ 44 curBit = (l2.val + nextBit) % 10 ; 45 nextBit = (l2.val + nextBit)/10 ; 46 ListNode node = new ListNode(curBit) ; 47 temp.next = node ; 48 temp = temp.next ; 49 l2 = l2.next ; 50 } 51 //判断最后的进位位是否为0 ,不为0则需要保存下一位 52 if(nextBit != 0){ 53 ListNode node = new ListNode(nextBit) ; 54 temp.next = node ; 55 } 56 return head ; 57 } 60 }
时间: 2025-01-01 10:37:09