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
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
- class Solution {
- public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
- int num1 = 0;
- int num2 = 0;
- int ret = 0;
- ListNode head = new ListNode(0);
- ListNode temp = head;
- while (l1!=null&&l2!=null){
- num1 = l1.val;
- num2 = l2.val;
- temp.next=new ListNode ((num1+num2+ret)%10);
- ret = (num1+num2+ret)/10;
- temp = temp.next;
- l1 = l1.next;
- l2 = l2.next;
- }
- if (l1==null&& l2!=null){
- while (l2!=null){
- num2 = l2.val;
- temp.next=new ListNode ((num2+ret)%10);
- ret = (num2+ret)/10;
- temp = temp.next;
- l2 = l2.next;
- }
- }
- if (l1!=null&& l2==null){
- while (l1!=null){
- num1 = l1.val;
- temp.next=new ListNode ((num1+ret)%10);
- ret = (num1+ret)/10;
- temp = temp.next;
- l1 = l1.next;
- }
- }
- if (ret>0){
- temp.next = new ListNode(ret); //别忘了
- }
- return head.next;
- }
- }
posted on 2019-01-30 09:23 WenjieWangFlyToWorld 阅读(95) 评论(0) 编辑 收藏 举报