Leetcode 2553. Separate the Digits in an Array
You are given an integer array nums
. The purpose of the function is to:
nums
to its constituent digits.n
is the number of elements in the input array and m
is the average number of digits in the numbers. Each number is converted to a string and each digit is processed individually.Here is the corresponding C++ code:
#include <vector>
#include <string>
std::vector<int> separateDigits(const std::vector<int>& nums) {
std::vector<int> result;
for (int num : nums) {
std::string numStr = std::to_string(num);
for (char digit : numStr) {
if(digit == '-') continue; // Skip negative sign
result.push_back(digit - '0');
}
}
return result;
}
std::vector<int> result;
prepares an empty vector to store the digits.std::string numStr = std::to_string(num);
converts each number to its string representation.for (char digit : numStr)
iterates through each character of the string. We ignore the negative sign if present.result.push_back(digit - '0');
converts the character to its integer form and adds it to the result array.result
vector containing all the digits in the required order.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?