Medium 2题 Add Two Numbers

来源:互联网 发布:淘宝卖家怎么查看总额 编辑:程序博客网 时间:2024/06/05 03:02

Question:

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


Solution:

/** * 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) {        ListNode res=new ListNode(0);        ListNode head=res;        int sum=0;        int carry=0;        while(l1!=null||l2!=null||carry!=0)        {            ListNode cur=new ListNode(0);            if(l1!=null)                sum+=l1.val;            if(l2!=null)                sum+=l2.val;            cur.val=(sum+carry)%10;            if(sum+carry>=10)                carry=1;//the carry can only be one            else                carry=0;            res.next=cur;            res=cur;            sum=0;            if(l1!=null)                l1=l1.next;            if(l2!=null)                l2=l2.next;        }        return head.next;    }}


第二遍写就好多了~综合了add two numbers ii

/** * 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 carry=0;        ListNode head=new ListNode(0);        ListNode cur=head;        while(l1!=null||l2!=null||carry!=0){            int tmp=0;            if(l1!=null)            {                tmp+=l1.val;                l1=l1.next;            }            if(l2!=null)            {                tmp+=l2.val;                l2=l2.next;            }            tmp+=carry;            carry=tmp/10;            ListNode tmpp=new ListNode(tmp%10);            cur.next=tmpp;            cur=cur.next;        }        return head.next;    }}


0 0