首页 > 代码库 > Add Two Numbers

Add Two Numbers

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

 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(null == l1)15             return l2;16         if(null == l2)17             return l1;18         ListNode head = new ListNode(0);19         ListNode ptr = head;20         int carry = 0;                                            //进位21         while(null != l1 && null != l2){22             ListNode temp = new ListNode(l1.val + l2.val);23             temp.next = null;24             ptr.next = temp;25             ptr = ptr.next;26             l1 = l1.next;27             l2 = l2.next;28         }29         while(null != l1){30             ListNode temp = new ListNode(l1.val);31             ptr.next = temp;32             temp.next = null;33             ptr = ptr.next;34             l1 = l1.next;35         }36         while(null != l2){37             ListNode temp = new ListNode(l2.val);38             ptr.next = temp;39             temp.next = null;40             ptr = ptr.next;41             l2 = l2.next;42         }43         //开始进位    44         ptr = head.next;45         while(null != ptr){46             ptr.val = ptr.val + carry;47             carry = ptr.val / 10;48             ptr.val %= 10;49             ptr = ptr.next;50         }51         if(1 == carry){52             ptr = head.next;53             while(null != ptr.next)54                 ptr = ptr.next;55             ListNode temp = new ListNode(1);56             temp.next = null;57             ptr.next = temp;58         }59         60         return head.next;61     }62 }

 

Add Two Numbers