« Back
in Leetcode Linked list Math read.

Leetcode 2 Add Two Numbers.

Problem 2 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

It is a very old problem, but the acceptance is not very high.

I misunderstood the problem at first, but it should not be so difficult. The numbers of two sets should be added up one by one, like the first number in first set add with the first number in second set. As it is a linkedlist, not very difficult to finish this.

Deal with the carry carefully, if you did the mathematics process bit by bit. Or another way to solve that problem is reduce the problem to numbers, then add them up.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int jinwei=0;
        int shuzi=0;
        ListNode pre=null;
        ListNode first=null;
        while(l1!=null && l2!=null){
            shuzi=(l1.val+l2.val+jinwei)%10;
            jinwei = (l1.val+l2.val+jinwei)/10;
            ListNode newnode=new ListNode(shuzi);
            if(first==null){
                first=newnode;
            }else{
            pre.next=newnode;}
            pre=newnode;
            l1=l1.next;
            l2=l2.next;
        }

        while(l1!=null ){
            shuzi=(l1.val+jinwei)%10;
            jinwei=(l1.val+jinwei)/10;

            ListNode newnode=new ListNode(shuzi);
            if(first==null){
                first=newnode;
            }else{
            pre.next=newnode;}
            pre=newnode;
            l1=l1.next;
        }

        while(l2!=null ){
            shuzi=(l2.val+jinwei)%10;
            jinwei=(l2.val+jinwei)/10;

            ListNode newnode=new ListNode(shuzi);
            if(first==null){
                first=newnode;
            }else{
            pre.next=newnode;}
            pre=newnode;
            l2=l2.next;
        }

        if (jinwei!=0){
            ListNode newnode=new ListNode(jinwei);
            pre.next=newnode;
            pre=newnode;
        }
        return first;
    }
}
comments powered by Disqus