Separate the Digits in an Array
Problem
Given an array of positive integers nums, return an array answer that contains the digits of each integer in nums after separating them in the same order they appear. To separate the digits of an integer is to break it into its individual digits, keeping their original ordering.
nums = [13,25,83,77][1,3,2,5,8,3,7,7]def separate_digits(nums):
answer = []
for num in nums:
for ch in str(num):
answer.append(int(ch))
return answer
function separateDigits(nums) {
const answer = [];
for (const num of nums) {
for (const ch of String(num)) {
answer.push(Number(ch));
}
}
return answer;
}
class Solution {
public int[] separateDigits(int[] nums) {
List<Integer> answer = new ArrayList<>();
for (int num : nums) {
for (char ch : Integer.toString(num).toCharArray()) {
answer.add(ch - '0');
}
}
int[] res = new int[answer.size()];
for (int i = 0; i < res.length; i++) res[i] = answer.get(i);
return res;
}
}
vector<int> separateDigits(vector<int>& nums) {
vector<int> answer;
for (int num : nums) {
string s = to_string(num);
for (char ch : s) {
answer.push_back(ch - '0');
}
}
return answer;
}
Explanation
The task is pure flattening: every number must be replaced by its sequence of digits, and all of those sequences are joined end to end in the original order.
The cleanest trick is to convert each number to a string. A string already lays the digits out left to right, so iterating over its characters gives them in the correct order. We turn each character back into an integer and append it.
Because we visit the numbers in input order, and within each number the characters in reading order, the final array preserves the exact digit ordering required — no reversing or sorting is involved.
An arithmetic alternative would repeatedly take num % 10 and divide by 10, but that produces digits in reverse, so you would have to flip them. The string approach avoids that bookkeeping entirely.
Example: [13,25,83,77]. 13 → "1","3" → 1,3; 25 → 2,5; 83 → 8,3; 77 → 7,7. Concatenated: [1,3,2,5,8,3,7,7].