Leetcode 2553. Separate the Digits in an Array
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
.
Example:
Input: nums = [13, 25, 83, 77]
Output: [1, 3, 2, 5, 8, 3, 7, 7]
Explanation:
- The digits of 13 are [1, 3]
- The digits of 25 are [2, 5]
- The digits of 83 are [8, 3]
- The digits of 77 are [7, 7]
Hence, the answer is [1, 3, 2, 5, 8, 3, 7, 7]
nums
positive integers?
nums
are positive.nums
be empty?
answer
that will store the separated digits.nums
.answer
list.answer
list.Here’s how we can achieve this in Java:
import java.util.ArrayList;
import java.util.List;
public class SeparateDigits {
public static List<Integer> separateDigits(int[] nums) {
List<Integer> answer = new ArrayList<>();
for (int num : nums) {
String numStr = String.valueOf(num);
for (char digitChar : numStr.toCharArray()) {
answer.add(Character.getNumericValue(digitChar));
}
}
return answer;
}
public static void main(String[] args) {
int[] nums = {13, 25, 83, 77};
System.out.println(separateDigits(nums)); // Output: [1, 3, 2, 5, 8, 3, 7, 7]
}
}
nums
and M is the average number of digits in each integer. Converting each number to a string takes O(M) time, and iterating over the list of digits also takes O(M) time for each number.answer
).This solution efficiently separates the digits while maintaining the order and handles all constraints provided by the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?