I am writing a C++ function which takes a positive number and returns an array containing its digits reversed.
#include <cmath>
#include <vector>
std::vector<int> digitize(unsigned long n) {
int x = 1;
for (int i = 1; n >= pow(10,i-1); ++i) { // Supposed to return the correct number of digits
x = i;
}
std::vector<int> result;
for (x; x > 0; --x) { // Takes the number of digits and begin assembling the array in reverse
result[x] = n / pow(10,x-1);
}
return result;
}
During compiling, it returned warnings, and I'm pretty sure the function hasn't even done what I intended it to do yet. One of the warnings had something to do with the for (x; x > 0; --x)
loop (some expression is unused). Shouldn't variable x carry over its value from the previous loop?
I tried modifying the second loop to use i instead of x, but as expected, the value and initialization of variable i didn't carry over from the first loop.
I would just rewrite the code to do a simpler approach.
n
being 0.n
and store that value in the vector using push_back
.n
by 10n
is 0Example:
#include <vector>
#include <iostream>
std::vector<int> digitize(unsigned long n)
{
std::vector<int> answer;
if ( n == 0 )
return {0};
while (n > 0)
{
answer.push_back(n % 10);
n /= 10;
}
return answer;
}
int main()
{
auto v = digitize(1232196);
for (auto val : v)
std::cout << val;
}
Output:
6912321