|
| 1 | +/** |
| 2 | + * Link: https://leetcode.com/problems/compute-decimal-representation/ |
| 3 | + * Title: Compute Decimal Representation |
| 4 | + * |
| 5 | + * Question: |
| 6 | + * You are given an integer n. Your task is to break it down into its decimal components. |
| 7 | + * For example: |
| 8 | + * n = 4321 → [4000, 300, 20, 1] |
| 9 | + * n = 5030 → [5000, 30] |
| 10 | + * n = 7 → [7] |
| 11 | + * |
| 12 | + * Return the decimal representation as an array of integers, excluding zeros. |
| 13 | + * |
| 14 | + * -------------------------------------------------------------------- |
| 15 | + * Approach: |
| 16 | + * - Start with place value = 1 (units place). |
| 17 | + * - While n > 0: |
| 18 | + * - Extract the last digit (digit = n % 10). |
| 19 | + * - If digit != 0, compute digit * place and store it. |
| 20 | + * - Update n by dividing it by 10. |
| 21 | + * - Update place by multiplying it by 10. |
| 22 | + * - Reverse the list since we collect from lowest place to highest. |
| 23 | + * - Convert the list into an integer array and return. |
| 24 | + * |
| 25 | + * -------------------------------------------------------------------- |
| 26 | + * Dry Run: |
| 27 | + * n = 5030 |
| 28 | + * place = 1 |
| 29 | + * digit = 0 → skip |
| 30 | + * n = 503, place = 10 |
| 31 | + * digit = 3 → add 30 |
| 32 | + * n = 50, place = 100 |
| 33 | + * digit = 0 → skip |
| 34 | + * n = 5, place = 1000 |
| 35 | + * digit = 5 → add 5000 |
| 36 | + * Result list = [30, 5000] |
| 37 | + * Reverse → [5000, 30] |
| 38 | + * Output = [5000, 30] |
| 39 | + * |
| 40 | + * -------------------------------------------------------------------- |
| 41 | + * Time Complexity: O(log10(n)) |
| 42 | + * - We process each digit once. |
| 43 | + * Space Complexity: O(log10(n)) |
| 44 | + * - We store at most one value per digit. |
| 45 | + */ |
| 46 | + |
| 47 | +class Solution { |
| 48 | + public int[] decimalRepresentation(int n) { |
| 49 | + List<Integer> base = new ArrayList<>(); |
| 50 | + int place = 1; |
| 51 | + while (n > 0) { |
| 52 | + int digit = n % 10; |
| 53 | + if (digit != 0) { |
| 54 | + base.add(digit * place); |
| 55 | + } |
| 56 | + n /= 10; |
| 57 | + place *= 10; |
| 58 | + } |
| 59 | + Collections.reverse(base); |
| 60 | + int[] list = new int[base.size()]; |
| 61 | + for (int i = 0; i < base.size(); i++) { |
| 62 | + list[i] = base.get(i); |
| 63 | + } |
| 64 | + return list; |
| 65 | + } |
| 66 | +} |
0 commit comments