Search code examples
c++arraysfunctionlong-integerdigits

Problem in digitizing a number and putting it in an array reversed


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.


Solution

  • I would just rewrite the code to do a simpler approach.

    1. Check for the special case of n being 0.
    2. Write a loop that gets modulo 10 of n and store that value in the vector using push_back.
    3. Divide n by 10
    4. Repeat steps 2) and 3) until n is 0

    Example:

    #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