LeetCode 2. Add Two Numbers

2. Add Two Numbers

Question

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

  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. class Solution {  
  10.     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {  
  11.         int num1 = 0;  
  12.         int num2 = 0;  
  13.         int ret = 0;  
  14.         ListNode head = new ListNode(0);  
  15.         ListNode temp = head;  
  16.         while (l1!=null&&l2!=null){  
  17.             num1 = l1.val;  
  18.             num2 = l2.val;  
  19.             temp.next=new ListNode ((num1+num2+ret)%10);  
  20.             ret = (num1+num2+ret)/10;  
  21.             temp = temp.next;  
  22.             l1 = l1.next;  
  23.             l2 = l2.next;  
  24.   
  25.         }  
  26.   
  27.         if (l1==null&& l2!=null){  
  28.   
  29.             while (l2!=null){  
  30.                 num2 = l2.val;  
  31.                 temp.next=new ListNode ((num2+ret)%10);  
  32.                 ret = (num2+ret)/10;  
  33.                 temp = temp.next;  
  34.                 l2 = l2.next;  
  35.             }  
  36.         }  
  37.         if (l1!=null&& l2==null){  
  38.   
  39.             while (l1!=null){  
  40.                 num1 = l1.val;  
  41.                 temp.next=new ListNode ((num1+ret)%10);  
  42.                 ret = (num1+ret)/10;  
  43.                 temp = temp.next;  
  44.                 l1 = l1.next;  
  45.             }  
  46.         }  
  47.           
  48.         if (ret>0){  
  49.             temp.next = new ListNode(ret);  //别忘了
  50.         }  
  51.   
  52.         return head.next;  
  53.     }  
  54. }  
原文地址:https://www.cnblogs.com/wwjldm/p/10336719.html