用java解决LeetCode(1)——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
解决方案:

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node=null;
        node=new ListNode(0);
        ListNode l=node;
        int c=0;
        while(true)
        {
            node.val=(l1.val+l2.val+c)%10; 
            c=(l1.val+l2.val+c)/10;
            if(l1.next==null&&l2.next==null) 
            {
                if(c==1) 
                {
                    node.next=new ListNode(1);
                    node=node.next;
                }
                break;
            }
            node.next=new ListNode(0);
            node=node.next;
            if((l1=l1.next)==null) l1=new ListNode(0);
            if((l2=l2.next)==null) l2=new ListNode(0);
        }
        return l;
    }
}

解法相对简单,适合初学者。

猜你喜欢

转载自blog.csdn.net/h9f3d3/article/details/51872804