C# solutions 202ms


  • 0
    /**
     * 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 nullStart=new ListNode(-1);
            ListNode realStart=nullStart;
            int overFlow=0;
            while(l1!=null||l2!=null)
            {
                int l1Value=l1==null?0:l1.val;
                int l2Value=l2==null?0:l2.val;
                int currentSum=l1Value+l2Value+overFlow;
                if(currentSum>=10)
                {
                    overFlow=1;
                    currentSum-=10;
                }
                else
                {
                    overFlow=0;
                }
                realStart.next=new ListNode(currentSum);
                realStart=realStart.next;
                l1=l1==null?null:l1.next;
                l2=l2==null?null:l2.next;
            }
            if(overFlow==1)
            {
                realStart.next=new ListNode(1);
            }
            return nullStart.next;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.