Problem · Linked List
Subtract Forward-Order Linked-List Numbers
Learn this problemProblem statement
Two nonempty singly linked lists represent nonnegative integers in forward digit order. Each node stores one decimal digit. Return a new forward-order linked list representing minuend - subtrahend.
The inputs have no leading zero unless the entire number is zero, and the value represented by minuend is at least the value represented by subtrahend. The result must have no leading zero; represent zero with one node containing 0. Do not convert either complete number to a built-in numeric type.
Function
subtractForwardOrder(minuend: ListNode, subtrahend: ListNode) → ListNodeExamples
Example 1
minuend = [7,2,4,3]subtrahend = [5,6,4]return = [6,6,7,9]The lists represent 7243 and 564. Their difference is 6679.
Example 2
minuend = [1,0,0,0]subtrahend = [1]return = [9,9,9]Subtracting 1 from 1000 propagates a borrow through three zero digits and yields 999.
Example 3
minuend = [5]subtrahend = [5]return = [0]Equal inputs have difference zero, represented by a single 0 node.
Constraints
- Each list contains between
1and10^5nodes. 0 <= node.val <= 9- Neither input has a leading zero unless it is the single-node number
0. - The represented value of
minuendis at least the represented value ofsubtrahend.