Convert Integer to the Sum of Two No-Zero Integers Problem
Description
LeetCode Problem 1317.
No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.
Given an integer n, return a list of two integers [a, b] where:
aandbare No-Zero integers.a + b = n
The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.
Example 1:
Input: n = 2
Output: [1,1]
Explanation: Let a = 1 and b = 1.
Both a and b are no-zero integers, and a + b = 2 = n.
Example 2:
Input: n = 11
Output: [2,9]
Explanation: Let a = 2 and b = 9.
Both a and b are no-zero integers, and a + b = 11 = n.
Note that there are other valid answers as [8, 3] that can be accepted.
Constraints:
2 <= n <= 10^4
Solution
Approach: Try Each Split
Try a = 1, 2, 3, ... with b = n - a, and return the first pair where neither number contains the digit 0. Checking a number means looking at its digits, either through its decimal string or by repeated % 10 and / 10.
The problem guarantees that a valid pair exists, and in practice one turns up after few tries. For most n, a = 1 already works. For n = 1010, the values b = 1009, 1008, ... all contain a 0 until a = 11 gives b = 999; even the worst n up to 104 needs only about a hundred tries. Any valid pair is accepted, for example [1,1] for n = 2 or [2,9] for n = 11.
Complexity: O(n log n) time in the worst case, since there are at most n - 1 splits and each check reads O(log n) digits; O(1) space.
class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
# Try a = 1, 2, 3, ...; a valid pair turns up quickly.
for a in range(1, n):
b = n - a
if "0" not in str(a) and "0" not in str(b):
return [a, b]
return [] # the problem guarantees an answer, so this is never reached