LeetCode Linked List Medium 2. Add Two Numbers

 Description


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.

 题目描述:两个非空链表,代表两个非负整数。链表从尾部到头部每一个元素代表非负整数的每一位的值。技术这两个数的值,并把结果放到一个链表中。

我的思路:链表长度不限,所以不能转成int 或者long 进行计算。同时 每一位进行计算的时候,会有进位产生。下面是我的解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode temp = res;
        bool flag = false;
        int sum = 0;
        while(l1 != null && l2 != null){
            temp.next = new ListNode((l1.val + l2.val + sum)%10);
            sum = (l1.val + l2.val + sum)/10;
            l1 = l1.next;
            l2 = l2.next;
            temp = temp.next;
            
        }
        while(l1 !=null){
            temp.next = new ListNode((l1.val + sum)%10);
            sum = (l1.val+sum)/10;
            l1 = l1.next;
            temp = temp.next;
        }
        while(l2 !=null){
            temp.next = new ListNode((l2.val + sum)%10);
            sum = (l2.val+sum)/10;
            l2 = l2.next;
            temp = temp.next;
        }
        if(sum != 0)
            temp.next=new ListNode(1);
        return res.next;
    }
}

 

 

posted @ 2018-09-05 11:18  C_supreme  阅读(139)  评论(0编辑  收藏  举报