Reputation: 1
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.
Upvotes: -2
Views: 177
Reputation: 13076
For example you can do something like this (not this answer is not only for you but also for more people starting out with C++)
#include <list>
#include <string>
#include <iostream>
// I just return a string since it is more easy to output the result
auto to_string(std::uint64_t value)
{
std::list<char> result;
while( value > 0 )
{
// with a list you can insert values in front of all other values
// push the new `digit` in front of everything else (the `0` is there to make a nice output string
// the module operator % will get the current last digit of the value
result.push_front(static_cast<char>(value % 10) + '0');
// dividing by 10 results in the "removal" of the last digit
value /= 10ul;
}
// convert the list of characters to a string (can be done for vector too)
return std::string{result.begin(), result.end()};
}
int main()
{
std::cout << to_string(1234) << "\n";
std::cout << to_string(12340) << "\n";
}
Upvotes: 1
Reputation: 35454
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
Upvotes: 2