LeetCode Ts-2553. Separate the Digits in an Array

    CodingLeetCode Js-String

    Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.
    To separate the digits of an integer is to get all the digits it has in the same order.
    For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].

    給定一個正整數陣列 nums,請回傳一個新陣列 answer。
    answer 由 nums 中每個整數的「各個位數」依序組成,且整數的順序與原陣列相同。
    例如,若整數為 10921,則它的位數分解為 [1, 0, 9, 2, 1]。
    

    Example 1:

    Input: nums = [13,25,83,77]
    Output: [1,3,2,5,8,3,7,7]
    Explanation: 
    - The separation of 13 is [1,3].
    - The separation of 25 is [2,5].
    - The separation of 83 is [8,3].
    - The separation of 77 is [7,7].
    answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order.
    

    Example 2:

    Input: nums = [7,1,3,9]
    Output: [7,1,3,9]
    Explanation: The separation of each integer in nums is itself.
    answer = [7,1,3,9].
    

    Solution:
    這題給了我們一個數值,並且把每個數字都獨立並放入陣列中。
    所以我們可以遍歷這個 nums 陣列,
    並且把得到的數值轉成字串後放入到 arr 陣列中即可。

    Code 1: BigO(n x k)

    function separateDigits(nums: number[]): number[] {
        let arr: number[] = [];
        for (const num of nums) {
            for (const char of num.toString()) {
                arr.push(Number(char));
            }
        }
        return arr;
    };
    

    FlowChart:
    Example 1

    Input: nums = [13,25,83,77]
    
    num 13, char 1, char 3
    num 25, char 2, char 5
    num 83, char 8, char 3
    num 77, char 7, char 7
    return [1,3,2,5,8,3,7,7]
    

    Example 2

    Input: nums = [7,1,3,9]
    
    num 13, char 1, char 3
    num 25, char 2, char 5
    num 83, char 8, char 3
    num 77, char 7, char 7
    return [1,3,2,5,8,3,7,7]