C# solution without /= 10


  • 0
    C

    Most solutions use carry /=10, isn't / a very slow operation?
    Also several solutions use ternary to add the l1 or l2 node value or add 0 when the node is null, why add 0?
    Does the compiler optimize that code and remove the + 0 operation?

        public ListNode AddTwoNumbers(ListNode l1, ListNode l2) 
        {
            ListNode result = new ListNode(0);
            ListNode tail = result;
            int digit = 0;
            
            while (l1 != null || l2 != null || digit != 0)
            {
                if (l1 != null)
                {
                    digit += l1.val;
                    l1 = l1.next;
                }
                
                if (l2 != null)
                {
                    digit += l2.val;
                    l2 = l2.next;
                }
                
                tail = tail.next = new ListNode(digit % 10);
                digit = digit > 9 ? 1 : 0;
            } 
            
            return result.next;
        }
    

Log in to reply
 

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