I need to create a function call convertToDecimal. This will then take an int array { 3, 2, 4 } and a length of the array, and will return a single integer where each part of the array is a digit in the new integer (324). To do this I would need to multiply:
3*10^2 +
2*10^1 +
4*10^0 = 324
I got the code to work but I would like to do it like the example above.
This is the code I have with the array { 1, 2, 3, 4, 5 }:
int sum2 = 0;
void convertToDecimal(int my_array[], int i)
{
for (int i = 0; i < 5; i++)
{
int num = my_array[i];
if (num != 0) {
while (num > 0) {
sum2 *= 10;
num /= 10;
}
sum2 += my_array[i];
}
else {
sum2 *= 10;
}
}
cout << "The numbers in the array together are " << sum2 << endl;
}
pow returns a double so the results are not guaranteed.
Since they are integers I would do something like
1 2 3 4 5 6 7 8 9
intconst base = 10;
int multiplier = 1;
int result = 0;
for(std::size_t i = arraySize - 1; i > -1; --i)
{
result += array[i] * multiplier;
multiplier *= base;
}