Skip to main content
2 of 3
added 760 characters in body
G. Sliepen
  • 69.3k
  • 3
  • 75
  • 180

Avoid mixing floating point and integer arithmetic

As mentioned by greybeard, there is a potential problem here:

const unsigned short n = log10(ULLONG_MAX);

ULLONG_MAX is larger than can be exactly represented by a double. This means the result might not be what you expect. The same goes for pow(10, n). While you can compensate for it, it is better to find a way to calculate the length of a number without using floating point math.

Keep it simple

Unless performance is a big concern, keep it simple. You don't have to know the number of digits up front if you push trailing digits to the front of the vector, like so:

vector<unsigned short> IntegerDigits(unsigned long long input)
{
    vector<unsigned short> output;

    while (input)
    {
        output.push_front(input % 10);
        input /= 10;
    }

    // Handle input being equal to 0
    if (output.empty())
    {
        output.push_back(0);
    }

    return output;
}

Pushing to the front of a std::vector is less efficient, but on the other hand you don't need the double<->int conversions, and you don't need to handle the leading zeros inside the loop.

Avoid using std::endl

Prefer using "\n" over std::endl, the latter is equivalent to the former, but also forces a flush of the output, which can be bad for performance.

Avoid backspaces in the output

You used a neat trick to get rid of the last comma without having to have extra logic inside the for-loop in main(). However, consider that the output might not just be for human consumption, but is written to a file and/or is parsed by another program. In that case, the \b characters are probably unexpected and might cause problems.

G. Sliepen
  • 69.3k
  • 3
  • 75
  • 180