I got an function that is taking in an int as parameter, and is going to output a int[].
The input int is a number between 0 and 1000. And my goal is to convert this number into an array where each index is a digit of the input number. And if there are two digits in the input number, the two least significant bits will be 0.
For example:
int num1 = 404;
int num2 = 42;
Will have output:
num1 = {4, 0, 4, 0}
num2 = {4, 2, 0, 0}
And so on..
Is there any clever way to achieve this? One though is to convert the number to a char*, but I'm not quite sure how to work with that either. I am kind of lost at the moment. Btw: this is not homework ;)
One way is using itoa function or std::stringstream class for converting a number to its symbolic representation. From there, you can subtract '0' from each character and get the corresponding digit as 0-9.
Another way is:
int tmpNum = num1;
int factor = 1;
int digits [4] = {0};
// Finding the most significant digit's weight
for (factor = 1; factor < num1; factor *= 10);
factor /= 10;
// Finding digits from most to least significant
for (int i = 0; tmpNum > 0; ++i)
{
digits[i] = tmpNum / factor;
tmpNum -= factor * digits[i];
factor /= 10;
}
This is essentially converting to 10-base (decimal) number. Or a binary-coded decimal, to be precise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With