Skip to content

Instantly share code, notes, and snippets.

@amullins83
Created June 14, 2016 21:30
Show Gist options
  • Save amullins83/e4aba28fdf87962ad9304f3d80a5fba9 to your computer and use it in GitHub Desktop.
Save amullins83/e4aba28fdf87962ad9304f3d80a5fba9 to your computer and use it in GitHub Desktop.
Counting Digits

#Counting Digits in C++

Theoretically, taking the ceiling of the base-10 logarithm of a number should give you the number of digits for that number, but watch for powers of 10. Does looping over the digits slow down the program? You can't tell without profiling it in practice.

#include <cmath>
#include <iostream>
#include <iomanip>
#include <vector>
#include <stdint.h>
using namespace std;
size_t countDigitsLog(int number)
{
return ceil(log10((float)number));
}
size_t countDigitsLoop(int number)
{
size_t digits = 0;
if (!number)
return 1;
number = abs(number);
while (number)
{
number /= 10;
++digits;
}
return digits;
}
int main()
{
int ints[] = {10, 100, 1000, 4192, 10000};
size_t count = sizeof(ints)/sizeof(ints[0]);
for (int i = 0; i < count; ++i)
{
cout << "Log-based count for " << setw(5) << ints[i] << " is: " << setw(5) << countDigitsLog(ints[i]) << endl;
cout << "Loop-based count for " << setw(5) << ints[i] << " is: " << setw(5) << countDigitsLoop(ints[i]) << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment