string: chars removal and divide digits into blocks - c++

The problem says that you have a string consisting of digits & special chars. All you have to do is to remove all the chars and divide the digits into blocks separated by '-'. The block holds 3 digits or 2 digits but cannot be 1 alone. For example:
input: "aasnd1df2d3dfg4gfd56f7gaad8ew9ds2sa1"
After the removal of the chars, it should be like "12345678921" and then it should be divided into blocks, so the final output would be like "123-456-789-21".
I made the char removal part, but I can't make the blocks division. Any ideas?
string removeNumbers(string str)
{
int current = 0;
string dig;
int len=0;
int ctr=0;
for(int i = 0; i < str.length(); i++){
if (isdigit(str[i])){
str[current] = str[i];
current++;
}
}
dig= str.substr(0,current);
return dig;
}

You first function works. However, it is a little bit too complicated and should be refactored. Also the name is wrong. It removes the NON-digits.
I will show a similar, but easier solution to you later in the code example.
Now the tricky part. You want to distribute the digits equally in a group with a given fixed size. I will explain the general approach with arbitrary group sizes to you.
Let us assume that you want to split an array of a given size into groups of a fixed size, here the array of digits (your string) into groups of size gs, in your example 3.
Then we can calculate the number of groups by a simple integer division. So, basically the number of elements in the array (number of digits in your string) devided by the group size. Since an integer division of a number by a group size will result in 0 for the first group-size elements, we will add an offset of one and get the simple formular:
const size_t numberOfResultingGroups = ((numberOfDigits-1) / groupSize) + 1 ;
This should be understandable. And how many elements will there be in one group? We can calculate this again with an integer division. So, number of elements (digits) divided by the group size. Also very straigtforward.
const size_t basicGoupSize = numberOfDigits / numberOfResultingGroups;
Also very easy to understand. But there may be a remainder as a result of the integer division. These remaining elements need also to be distributed.
We could calculate the remainder with a modulo division, but also in a classical way:
int digitsToDistribute = numberOfDigits - (numberOfResultingGroups * basicGoupSize);
Also this is simple to understand.
And note, the remainder (the digitsToDistribute) can of course never be bigger than the number of groups.
We can then in a loop use the "basicGoupSize" and add a 1 to it, as long as there are remaining "digitsToDistribute". So, in each loop run, we will check, if there are still remaining bytes to distribute, and, in case of yes, add 1 to the "basicGoupSize" and the decrement the "digitsToDistribute".
And so all bytes will be evenly distributed.
Next is the handling of a dash. Many people think of it like print something, then dash, then something, then dash, then something, then dash aso.
But the handling of the last dash may be difficult. And so, we turn the sequence around and print a dash, followed by something, followed by a dash, followed by something aso. And we simply suppress the first dash.
Everything together will lead us to the solution (This is one of many possible solutions):
#include <iostream>
#include <string>
// Remove all non-digits from a string
std::string removeNonDigits(const std::string &str)
{
std::string dig;
for (unsigned int i = 0; i < str.length(); i++) {
if (::isdigit(str[i])) {
dig += str[i];
}
}
return dig;
}
int main() {
// Ourtest string
std::string test{ "aasnd1df2d3dfg4gfd56f7gaad8ew9ds2sa1sdf34sdff56sdff78sdf" };
// Remove all non digits
std::string digits{ removeNonDigits(test) };
// Our group length will be 3 (can be anything else)
constexpr size_t groupSize{ 3u };
// How many digitsdowe haveinour test string
const size_t numberOfDigits = digits.length();
// Trivial case: Number of digits is smaller than the desired group size. Simply print it
if (numberOfDigits < groupSize) {
std::cout << digits << '\n';
}
else {
// Ok, now we want to build groups and distribute remainders
// How many goups will we have? Integer division by group size (corrected for a 1 offset)
const size_t numberOfResultingGroups{ ((numberOfDigits-1) / groupSize) + 1 };
// A basic group will have this size. Integer division of number Of digits by number of groups
const size_t basicGoupSize{ numberOfDigits / numberOfResultingGroups };
// Maybe not all digits are used up. This is the remainder.
// We will add 1 to the basic group size as long as there are remaining digits
int digitsToDistribute = numberOfDigits - (numberOfResultingGroups * basicGoupSize);
// Handling of dashes. We will notprint a dash in front of the FIRST group
bool printDashInFrontOfGroup = false;
// Start position of substring
size_t stringStartPos{};
// No print all groups
for (size_t i{}; i < numberOfResultingGroups; ++i) {
// Length of group. So base length + 1, as long as there are remaining digits to distribute
const size_t length = basicGoupSize + (((digitsToDistribute--) > 0) ? 1 : 0);
// Print dash and sub string
std::cout << (std::exchange(printDashInFrontOfGroup, true)?"-":"") << digits.substr(stringStartPos, length);
// And,next start position
stringStartPos += length;
}
}
return 0;
}
Edit
Some additional note:
All the above algorithm is deterministic. It will give the mathematical correct solution. Predictable. For different group sizes.
As a basic rule. Make your design, the mathematics and the algorithm before start coding. Then implement everything.
Example: Removing non digits from a string in C++ is a really very short one-liner:
// Remove all-non-digits
test = std::regex_replace(test, std::regex(R"([^0-9])"), "");
That is basically very simple and actually a no brainer. Anyway. People may do it differently, or more complicated. For whatever reason.
And as said, if you do your design before coding then you can come up with really compact solutions. One of many possible examples:
#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <vector>
#include <experimental/iterator>
auto splitToEqualParts(const std::string s, const size_t groupSize) {
std::vector<std::string> result{}; // Here we will store all the split string parts
int toDistribute = (int)s.size() - (((((int)s.size() - 1) / (int)groupSize) + 1) * (int)(s.size() / ((((int)s.size() - 1) / (int)groupSize) + 1)));
// Add all sub-string parts to result vector
for (size_t i{}, pos{}, length{}; i < (size_t)((((int)s.size() - 1) / (int)groupSize) + 1); ++i, pos += length) {
length = (s.size() / ((((int)s.size() - 1) / (int)groupSize) + 1)) + (toDistribute-- > 0) * 1;
result.push_back(s.substr(pos, length));
}
return result;
}
int main() {
// Some test string
std::string test{ "aasnd1df2d3dfg4gfd56f7gaad8ew9ds2sa1sdf34sdff56sdff78sdf" };
// Remove all-non-digits
test = std::regex_replace(test, std::regex(R"([^0-9])"), "");
// Split into equal parts
std::vector part{ splitToEqualParts(test, 3) };
std::copy(part.begin(), part.end(), std::experimental::make_ostream_joiner(std::cout, "-"));
return 0;
}
Compiled and tested with GCC and Clang. Using C++17.
Of course the common sub expressions maybe put in const variables. But basically no need. An optimizing compiler will do it for you.
The above will work for all group sizes (>0) and any number of digits in the string . . .

I suggest
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string remove_chars(string & s)
{
string inter_result;
for_each(s.begin(), s.end(), [&inter_result](char c) { if (isdigit(c)) inter_result += c; });
size_t length = inter_result.length();
if (length <= 3)
{
return inter_result;
}
string result;
size_t pos = 0, step = 3;
while (pos < length)
{
if (length - pos - 3 == 1) step = 2;
if (result.length() > 0)
{
result += "-";
}
result += inter_result.substr(pos, step);
pos += step;
}
return result;
}
int main()
{
string s = "aasnd1df2d3dfg4gfd56f7gaad8ew9ds2sa1";
cout << remove_chars(s) << endl;
return 0;
}

Related

How to solve Permutation of a phone number problem

The Problem:
A company is distributing phone numbers to its employees to make things easier. the next digit cannot be equal to the last is the only rule for example 0223 is not allowed while 2023 is allowed. At least three digits will be excluded every time. Write a function that takes in a length of the phone number and the digits that will be excluded. The function should print all possible phone numbers.
I got this question in an interview and I have seen one like it before at my university. It is a permutation problem. My question is what is the best way or decent way to solve this without a million for loops.
I do understand that this is technically how it works
length of phone number = 3;
[0-9], [0-9] excluding the last digit, [0-9] excluding the last digit
but I am unsure on how the best way to turn this into code. Any language is accepted!
thank you:
Also I might be asking this in the wrong place. please let me know if I am.
A simple way to solve this problem could be using Recursion. Here's my commented C++ code:
void solve(int depth, int size, vector <int> &curr_seq){
// If the recursion depth is equal to size, that means we've decided size
// numbers, which means that curr_seq.size() == size. In other words, we've
// decided enough numbers at this point to create a complete phone number, so
// we print it and return.
if(depth == size){
for(int item : curr_seq){
cout << item;
}
cout << "\n";
return;
}
// Try appending every possible digit to the current phone number
for(int i = 0; i <= 9; ++i){
// Make sure to only append the digit i if it is not equal to the last digit
// of the phone number. We can also append it, however, if curr_seq
// is empty (because that means that we haven't decided the 1st digit yet).
if(curr_seq.empty() || curr[curr.size() - 1] != i){
curr_seq.push_back(i);
solve(depth + 1, size, curr);
curr_seq.pop_back();
}
}
}
I think I like the recursive solution, but you can also just generate all permutations up to the limit (iterate), filter out any with repeating digits, and print the successful candidates:
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
// Because C/C++ still has no integer power function.
int ipow(int base, int exp) {
int result = 1;
for (;;) {
if (exp & 1)
result *= base;
exp >>= 1;
if (!exp)
return result;
base *= base;
}
}
void noconsec(const int len) {
int lim = ipow(10, len);
// For e.g. len 4 (lim 10000),
// obviously 00xx won't work, so skip anything smaller than lim / 100.
int start = (len <= 2) ? 0 : (lim / 100);
for (int num = start;num < lim;num++) {
// Convert to string.
std::stringstream ss;
ss << std::setw(len) << std::setfill('0') << num;
std::string num_s = ss.str();
// Skip any consecutive digits.
bool is_okay = true;
auto prev_digit = num_s[0];
for (int digit_idx = 1;digit_idx < num_s.length();digit_idx++) {
auto digit = num_s[digit_idx];
if (prev_digit == digit) {
is_okay = false;
}
prev_digit = digit;
}
// Output result.
if (is_okay) {
cout << num_s << "\n";
}
}
}
int main(const int argc, const char * const argv[]) {
noconsec(4);
}
Differences to note, this needs an integer power function to compute the limit. Converting an int to a string and then checking the string is more complex than constructing the string directly. I guess it could be useful if you have a list of integers already, but mostly I did it for fun.

Find the reverse of a number (ex : 2500 reverse 0025) without the help of string or character

Is there any technique for finding the reverse when there are zeros at the end.
While following the algorithm of %10 technique the result is 52. And the 0's are missing.
I have got the reverse by just printing the reminders (with 0's). But I am not satisfied as I wish to display the answer as the value in a variable.
Kindly tell me is there any technique to store a value 005 to a variable and also to display 005 (please don't use String or Character or array).
Numbers are stored as binary 0 and 1 and so they always have leading 0's which are chopped off. e.g. a 64-bit integer has 64-bit bits, always and when it is printed these leading 0's are dropped.
You need to know how many leading zeros you want to keep and only use that many when you print. i.e. you can record how many leading zeros there were in a normal number without encoding it e.g. by adding a 1 at the start. i.e. 0052 is recorded as 10052 and you skip the first digit when you print.
If you need to store a single value you can do the following. I use do/while so that 0 becomes 10 and is printed as 0. The number 0 is the one place where not all leading zeros are dropped (as it would be empty otherwise)
This appears to be the solution you want and it should be basically the same in C or C++
static long reverse(long num) {
long rev = 1; // the 1 marks the start of the number.
do {
rev = rev * 10 + num % 10;
num /= 10;
} while(num != 0);
return rev;
}
// make the reversed number printable.
static String toStringReversed(long num) {
return Long.toString(num).substring(1);
}
long l = reverse(2500); // l = 10052
An alternative is to print the digits as you go and thus not need to store it.
e.g.
static void printReverse(long l) {
do {
System.out.print(l % 10);
l /= 10;
} while(l != 0);
}
or you can have the input record the number of digits.
static void printReverse(long l, int digits) {
for(int i = 0; i < digits; i++) {
System.out.print(l % 10);
l /= 10;
}
}
// prints leading zero backwards as well
printReverse(2500, 6); // original number is 002500
prints
005200
You cannot represent an integer with leading zeros as a single integer variable, that information is simply not part of the way bits are allocated in an integer. You must use something larger, i.e. a string or an array of individual (small integer) digits.
You can't store them in a simple integer variable because in binary format
00101 is same as 000101 which is same as 101 which only results into 5. The convertion between a decimal number and binary numbers don't consider leading zeroes so it is not possible to store leading zeroes with the same integer variable.
You can print it but you can't store the leading zeroes unless you use array of ints...
int num = 500;
while(num > 0)
{
System.out.print(num%10);
num = num/10;
}
Alternatively you can store the count of leading zeroes as a separate entity and combine them when ever you need to use. As shown below.
int num = 12030;
boolean leading=true;
int leadingCounter = 0;
int rev = 0;
while(num > 0)
{
int r = num%10;
if(r == 0 && leading == true)
leadingCounter++;
else
leading = false;
rev = rev*10 + r;
num = num/10;
}
for(int i = 1; i <= leadingCounter ; i++)
System.out.print("0");
System.out.println(rev);
I think the accepted answer is a good one, in that it both refutes the parts of the question that are wrong and also offers a solution that will work. However, the code there is all Java, and it doesn't expose the prettiest API. Here's a C++ version that based on the code from the accepted answer.
(Ha ha for all my talk, my answer didn't reverse the string! Best day ever!)
After going back to school and getting a degree, I came up with this answer: it has the makes the somewhat dubious claim of "not using strings" or converting any values to string. Can't avoid characters, of course, since we are printing the value in the end.
#include <ostream>
#include <iostream>
class ReverseLong {
public:
ReverseLong(long value) {
long num = value;
bool leading = true;
this->value = 0;
this->leading_zeros = 0;
while (num != 0) {
int digit = num % 10;
num = num / 10;
if (leading && digit == 0) {
this->leading_zeros += 1;
} else {
this->value = this->value * 10 + digit;
leading = false;
}
}
};
friend std::ostream & operator<<(std::ostream& out, ReverseLong const & r);
private:
long value;
int leading_zeros;
};
std::ostream & operator<<(std::ostream& out, ReverseLong const & r) {
for (int i =0; i < r.leading_zeros; i++) {
out << 0;
}
out << r.value;
return out;
};
int main () {
ReverseLong f = ReverseLong(2500); // also works with numbers like "0"!
std::cout << f << std::endl; / prints 0052
};

How to get one individual digit from a number that has more than one digit in it

So I have a four digit number that is player-input in a simple puzzle I am making, I want to be able to check each digit, say I want to check the second digit to the right, if the number happens to be 4601 then of course it will be 6 but is their a faster way other than testing every single four digit number?
I found a few results with search but they didn't help, they just confused me more, please phrase any answers so anyone can understand them.
Also i am using c++.
To retrieve the second most significant (base ten) digit from an arbitrary integer i you could do:
while (i >= 100)
i /= 10;
return i % 10;
Of course, this assumes the number greater than or equal to 10 to begin with. If you need to preserve the number, then you will (obviously) want to be operating on a copy.
EDIT:
One could define a function for extracting an arbitrary digit using either arithmetic or string operations.
Arithmetic solution:
int extractDigit(size_t digit, int n) {
int mask = 1;
while ( digit --> 0 )
mask *= 10;
if (n < mask / 10) { // insufficient digits
return -1; // or some other appropriate error handling.
while ( n >= mask )
n /= mask;
return n % 10;
}
String solution:
#include <sstream>
#include <string>
using std::string;
using std::stringstream;
int extractDigit(size_t digit, int n) {
string result = static_cast<stringstream&>(stringstream() << n).str();
if (result.size() < digit) {
return -1;
}
return result[digit-1] - '0';
}
Both of these solutions implicitly assume that n will be non-negative. You could enforce this pre-condition by using an unsigned data type if you need to. Also, both of these functions are defining the digit positions such that the most significant is in position 1, and the positions increase to the right.
I am not guessing anything about what you going to do after you have the digit.But if its only the digit you want to have then you could use below:
int a=1234;
char b[4];
sprintf(b,"%d",a);
char c=b[1];
Now c has the second digit of your 4 digit number.
like wise you can access all the digits using the index to character array b
for a c++ equivalent pls see below:
std::ostringstream out;
out << age;
Now out.str()[1] will show the second digit.
You can read the number as an int and convert it to a char array and check each char as a digit
Example:
char digits[5];
int number;
//Read number in
scanf("%d",&number);
//Make sure it's 4 digits
number%=10000;
//Convert it to a char array
sprintf(digits,"%d",number)
if(digits[1]=='6')
{
//do stuff
}

compare two alphanumeric string

I need to compare string into following way. Can anyone provide me some insight or algorithm in c++.
For example:
"a5" < "a11" - because 5 is less than 11
"6xxx < 007asdf" - because 6 < 7
"00042Q < 42s" - because Q < s alphabetically
"6 8" < "006 9" - because 8 < 9
I suggest you look at the algorithm strverscmp uses - indeed it might be that this function will do the job for you.
What this function does is the following. If both strings are equal,
return 0. Otherwise find the position between two bytes with the
property that before it both strings are equal, while directly after
it there is a difference. Find the largest consecutive digit strings
containing (or starting at, or ending at) this position. If one or
both of these is empty, then return what strcmp(3) would have
returned (numerical ordering of byte values). Otherwise, compare both
digit strings numerically, where digit strings with one or more
leading zeros are interpreted as if they have a decimal point in front
(so that in particular digit strings with more leading zeros come
before digit strings with fewer leading zeros). Thus, the ordering is
000, 00, 01, 010, 09, 0, 1, 9, 10.
Your examples only show digits, letters, and spaces. So for the moment I'll assume you ignore every other symbol (effectively treat them as spaces). You also seem to want to treat uppercase and lowercase letters as equivalent.
It also appears that you interpret runs of digits as a "term" and runs of letters as a "term", with any transition between a letter and a digit being equivalent to a space. A single space is considered equivalent to any number of spaces.
(Note: You are conspicuously missing an example of what to do in cases like:
"5a" vs "a11"
"a5" vs "11a"
So you have to work out what to do when you face a comparison of a numeric term with a string term. You also don't mention intrinsic equalities...such as should "5 a" == "5a" just because "5 a" < "5b"?)
One clear way of doing this would be turn the strings into std::vector of "terms", and then compare these vectors (rather than trying to compare the strings directly). These terms would be either numeric or string. This might help get you started, especially the STL answer:
how to split a string value that contains characters and numbers
Trickier methods that worked on the strings themselves without making an intermediary will be faster in one-off comparisons. But they'll likely be harder to understand and modify, and perhaps slower if you are going to repeatedly compare the same structures.
A nice aspect of parsing into a structure is that you get an intrinsic "cleanup" of the data in the process. Getting the information into a canonical form is often a goal in programs that are tolerating such a variety of inputs.
I'm assuming that you want the compare to be done in this order: presence of digits in range 1-9; value of digits; number of digits; value of the string after the digits.
It's in C, but you can easily transform it into using the C++ std::string class.
int isdigit(int c)
{
return c >= '1' && c <= '9';
}
int ndigits(const char *s)
{
int i, nd = 0;
int n = strlen(s);
for (i = 0; i < n; i++) {
if (isdigit(s[i]))
nd++;
}
return nd;
}
int compare(const char *s, const char *t)
{
int sd, td;
int i, j;
sd = ndigits(s);
td = ndigits(t);
/* presence of digits */
if (!sd && !td)
return strcasecmp(s, t);
else if (!sd)
return 1;
else if (!td)
return -1;
/* value of digits */
for (i = 0, j = 0; i < sd && j < td; i++, j++) {
while (! isdigit(*s))
s++;
while (! isdigit(*t))
t++;
if (*s != *t)
return *s - *t;
s++;
t++;
}
/* number of digits */
if (i < sd)
return 1;
else if (j < td)
return -1;
/* value of string after last digit */
return strcasecmp(s, t);
}
Try this and read about std::string.compare:
#include <iostream>
using namespace std;
int main(){
std::string fred = "a5";
std::string joe = "a11";
char x;
if ( fred.compare( joe ) )
{
std::cout << "fred is less than joe" << std::endl;
}
else
{
std::cout << "joe is less than fred" << std::endl;
}
cin >> x;
}

Convert integer to array

I would like to convert an integer into an array, so that it looks like the following:
int number = 123456 ;
int array[7] ;
with the result:
array[0] = 1
array[1] = 2
...
array[6] = 6
Perhaps a better solution is to work backwards:
123456 % 10 = 6
123456 / 10 = 12345
12345 % 10 = 5
12345 / 10 = 1234
just use modular arithmetic:
int array[6];
int number = 123456;
for (int i = 5; i >= 0; i--) {
array[i] = number % 10;
number /= 10;
}
You can extract the last digit of the number this way:
int digit = number % 10;
number /= 10;
Note that you should also check whether number is positive. Other values require additional handling.
Here what I came up with, the integerToArray function returns a vector that is converted from the integer value. you can test it with the main function as well:
#include <iostream>
#include <vector>
using namespace std;
vector <int> integerToArray(int x)
{
vector <int> resultArray;
while (true)
{
resultArray.insert(resultArray.begin(), x%10);
x /= 10;
if(x == 0)
return resultArray;
}
}
int main()
{
vector <int> temp = integerToArray(1234567);
for (auto const &element : temp)
cout << element << " " ;
return 0;
}
//outputs 1 2 3 4 5 6 7
Take the log10 of the number to get the number of digits. Put that in, say pos, then, in a loop, take the modulo of 10 (n % 10), put the result in the array at position pos. Decrement pos and divide the number by 10. Repeat until pos == 0
What did you want to do with the sign if it's negative?
#include <cmath>
#include <vector>
std::vector<int> vec;
for (int i = log10(input); i >= 0; i--)
{
vec.push_back(input / int(std::pow(10, i)) % 10);
}
Might be a good approach, I think
The easiest way I can imagine now is:
char array[40];
int number = 123456;
memset(array, 0x00, sizeof(array));
sprintf(array, "%d", number);
Additionally you can convert each digit to int just subtracting the char value by 0x30.
EDIT: If this is a homework, your teacher you probably ask you to write the program using % operator though (example 12 % 10 = 2). If this is the case, good homework ;-)
You can use modulus to determine the last digit.
And you can use division to move another digit to the last digit's place.
You can't simply "convert" it. The integer is not represented in software in decimal notation. So the individual digits you want don't exist. They have to be computed.
So, given an arbitrary number, how can you determine the number of ones?
We could divide by ten, and then take the remainder: For 123, the division would give 12, and then there's a remainder of 3. So we have 3 ones. The 12 tells us what we have past the ones, so it can be our input for the next iteration. We take that, divide by 10, and get 1, and a remainder of 2. So we have 2 in the tens place, and 1 left to work with for the hundreds. Divide that by 10, which gives us zero, and a remainder of 1. So we get 1 in the hundreds place, 2 in the tens place, and 3 in the ones place. And we're done, as the last division returned zero.
See SO question Language showdown: Convert string of digits to array of integers? for a C/C++ version (as well as other languages).
if this is really homework then show it your teacher - just for fun ;-)
CAUTION! very poor performance, clumsy way to reach the effect you expect and generally don't do this at home(work) ;-)
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
typedef std::vector< int > ints_t;
struct digit2int
{
int operator()( const char chr ) const
{
const int result = chr - '0';
return result;
}
};
void foo( const int number, ints_t* result )
{
std::ostringstream os;
os << number;
const std::string& numberStr = os.str();
std::transform(
numberStr.begin(),
numberStr.end(),
std::back_inserter( *result ),
digit2int() );
}
int main()
{
ints_t array;
foo( 123456, &array );
std::copy(
array.begin(),
array.end(),
std::ostream_iterator< int >( std::cout, "\n" ) );
}
If you wanted to turn it into a string then it would be really easy, just do what everyone else is saying about using the % operator:
Let's say num = 123, we can do this:
string str;
while (num > 0)
{
str = (num % 10) + str; //put last digit and put it into the beginning of the string
num = num /10; //strip out the last digit
}
Now you can use str as an array of chars. Doing this with an array is a hassle because putting things in the beginning of an array requires you to shift everything else. What we can do is, instead of putting each digit into a string, we can put it into a stack. It will put it in a backwards order like this: 3 2 1. Then we can pop off the top number one by one and put that into an array in the correct order. You array will look like this: 1 2 3. I will leave the implementation to you since this is homework.
#Broam has a good solution, but like he stated, it's for working backwards. I think the OP or whoever comes looking into this thread will want it forwards and that's why I'm posting this. If you have a better solution, please reply, I'm interested as well.
To convert an integer to array, you can do the steps below:
Get the total number of digits in a number to which we want to convert to
array.For this purpose, we will use count_digits() function which will return total no of digits after ignoring leading zeros.
digits = count_digits(n);
Now we will dynamically allocate memory for our resulting array, just like
int* arr = new int[count_digits(n)]
After allocating memory, we will populate the array using the for loop below
int digits = count_digits(num);
for (int i = digits; i > 0; i--){
arr[i-1] = num % 10;
num = num / 10;
}
After performing the steps above, we will be able to convert an integer to array. Remember, num is the number that we want to convert into array and digits is the variable which gives us the number of digits in a given number ignoring leading zeros.