LeetCode之Add Two Numbers

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.

 

题目不难,直接上代码。

/**
 * 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) {
        ListNode result = null, tmp = null;//tmp作为指针使用,进行移动
        int n = 0;
        int v1 = 0, v2 = 0;
        while(l1 != null || l2 != null)
        {
            if(l1 != null)
            {
                v1 = l1.val;
            }
            if(l2 != null)
            {
                v2 = l2.val;
            }
            
            //第一次进行计算
            if(result == null)
            {
                result = new ListNode((v1 + v2) % 10);
                tmp = result;
                n = (v1 + v2)/10;
            }
            else
            {
                ListNode next = new ListNode((v1 + v2 + n) % 10);//避免超过10,我们只需要个位数字
                tmp.next = next;
                tmp = next;
                n = (v1 + v2 + n) / 10;
            }
           
            v1 = 0;
            v2 = 0;
            if (l1 != null)
            {
                l1 = l1.next; 
            }
            if (l2 != null)
            {
                l2 = l2.next;
            }
        }
        if(n > 0)
        {
            tmp.next = new ListNode(n);
        }
        return result;
    }
}

 

posted @ 2018-01-03 17:33  woniu4  阅读(139)  评论(0编辑  收藏  举报