Welcome to Subscribe On Youtube
3697. Compute Decimal Representation
Description
You are given a positive integer n.
A positive integer is a base-10 component if it is the product of a single digit from 1 to 9 and a non-negative power of 10. For example, 500, 30, and 7 are base-10 components, while 537, 102, and 11 are not.
Express n as a sum of only base-10 components, using the fewest base-10 components possible.
Return an array containing these base-10 components in descending order.
Example 1:
Input: n = 537
Output: [500,30,7]
Explanation:
We can express 537 as 500 + 30 + 7. It is impossible to express 537 as a sum using fewer than 3 base-10 components.
Example 2:
Input: n = 102
Output: [100,2]
Explanation:
We can express 102 as 100 + 2. 102 is not a base-10 component, which means 2 base-10 components are needed.
Example 3:
Input: n = 6
Output: [6]
Explanation:
6 is a base-10 component.
Constraints:
1 <= n <= 109
Solutions
Solution 1: Simulation
We can repeatedly perform modulo and division operations on $n$. Each modulo result multiplied by the current position value $p$ represents a decimal component. If the modulo result is not $0$, we add this component to our answer. Then we multiply $p$ by $10$ and continue processing the next position.
Finally, we reverse the answer to arrange it in descending order.
The time complexity is $O(\log n)$, where $n$ is the input positive integer. The space complexity is $O(\log n)$ for storing the answer.
-
class Solution { public int[] decimalRepresentation(int n) { List<Integer> parts = new ArrayList<>(); int p = 1; while (n > 0) { int v = n % 10; n /= 10; if (v != 0) { parts.add(p * v); } p *= 10; } Collections.reverse(parts); int[] ans = new int[parts.size()]; for (int i = 0; i < parts.size(); ++i) { ans[i] = parts.get(i); } return ans; } } -
class Solution { public: vector<int> decimalRepresentation(int n) { vector<int> ans; long long p = 1; while (n > 0) { int v = n % 10; n /= 10; if (v != 0) { ans.push_back(p * v); } p *= 10; } reverse(ans.begin(), ans.end()); return ans; } }; -
class Solution: def decimalRepresentation(self, n: int) -> List[int]: ans = [] p = 1 while n: n, v = divmod(n, 10) if v: ans.append(p * v) p *= 10 ans.reverse() return ans -
func decimalRepresentation(n int) []int { ans := []int{} p := 1 for n > 0 { v := n % 10 n /= 10 if v != 0 { ans = append(ans, p*v) } p *= 10 } slices.Reverse(ans) return ans } -
function decimalRepresentation(n: number): number[] { const ans: number[] = []; let p: number = 1; while (n) { const v = n % 10; n = (n / 10) | 0; if (v) { ans.push(p * v); } p *= 10; } ans.reverse(); return ans; }