Problem
A decimal number is called deci-binary if each of its digits is either 0
or 1
without any leading zeros. For example, 101
and 1100
are deci-binary, while 112
and 3001
are not.
Given a string n
that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 – Maximum Digit Greedy
Intuition
Each deci-binary number can only contribute 1 to each digit position (since its digits are only 0 or 1). To form a digit d in any position, we need at least d deci-binary numbers stacked so that their sum at that position is d. Therefore, the minimum number of deci-binary numbers needed is equal to the largest digit in n.
Approach
- Scan through all digits of n.
- Find the maximum digit (let’s call it x).
- The answer is x, because you need at least x deci-binary numbers to sum up to n at the position where n has digit x.
Example (Step by Step Construction):
Let n = “135”. The digits are 1, 3, 5, so the maximum is 5. We need 5 deci-binary numbers, each of length 3:
|
|
Now, for each digit position:
- For the first digit (1): fill the first 1 number with 1 at position 1:
- a1 = 1__
- For the second digit (3): fill the first 3 numbers with 1 at position 2:
- a1 = 11_
- a2 = 01_
- a3 = 01_
- For the third digit (5): fill the first 5 numbers with 1 at position 3:
- a1 = 111
- a2 = 011
- a3 = 011
- a4 = 001
- a5 = 001
So the five deci-binary numbers are:
|
|
Their sum is 111 + 11 + 11 + 1 + 1 = 135.
Visual proof:
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity: O(L), where L is the length of n. We scan each digit once to find the maximum.
- 🧺 Space complexity: O(1), since we only use a constant number of variables.