/*
 * 演算法 / Algorithm:
 *   逐個整數處理；用 x%10 / x/=10 反序取出每一位數，暫存到 buf，
 *   再把 buf 反向複製到答案陣列，順序就恢復成「高位 → 低位」。
 *   For each integer, peel digits via x%10 / x/=10 (which yields them in
 *   reverse), stash into a small buffer, then copy back reversed so the
 *   final order is most-significant first.
 */

#include <stdlib.h>   // for malloc / 提供 malloc

int* separateDigits(int* nums, int numsSize, int* returnSize) {
    // 每個數字 ≤ 10^5，最多 6 位；總長 ≤ 6 * numsSize 已綽綽有餘
    // Each number ≤ 10^5 has at most 6 digits, so 6*numsSize is a safe upper bound.
    int cap = 6 * numsSize;

    // malloc 在 heap 配置一塊空間，回傳指向第一個 int 的指標
    // malloc allocates the buffer on the heap; we return this pointer to LeetCode.
    int* ans = (int*)malloc(sizeof(int) * cap);

    int idx = 0;  // ans 中下一個要寫入的位置 / next write slot in ans

    // 依序處理 nums 中的每一個整數 / iterate over each input number
    for (int i = 0; i < numsSize; i++) {
        int x = nums[i];   // 取出當前整數的「複本」以便破壞性地除以 10 / mutable copy

        int buf[8];        // 暫存反序數字；最多 6 位，給 8 是保險 / scratch buffer
        int cnt = 0;       // buf 內目前已存的位數 / how many digits collected

        // 用 mod / div 從低位往高位剝出每一位
        // Peel digits from least-significant to most-significant.
        // 題目保證 nums[i] >= 1，所以 x 一開始一定 > 0，至少跑一次
        // The constraint nums[i] >= 1 guarantees the loop runs at least once,
        // so we don't need a special case for x == 0.
        while (x > 0) {
            buf[cnt++] = x % 10;  // 取得最後一位 / extract trailing digit
            x /= 10;              // 砍掉最後一位 / drop trailing digit
        }

        // 反向把 buf 倒回 ans：buf 是反序的，從尾巴往前讀就是正序
        // Copy buf into ans in reverse so the digits regain MSB-first order.
        for (int j = cnt - 1; j >= 0; j--) {
            ans[idx++] = buf[j];  // 寫入並推進 idx / write & advance
        }
    }

    // 透過 returnSize 指標把答案長度回報給 LeetCode
    // Tell the harness how long the answer array is via the out-parameter.
    *returnSize = idx;
    return ans;  // LeetCode 之後會負責 free / harness frees this later
}
