Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get the length of the decimal representation of an int in C++?

Tags:

c++

What's the best way to write

int NumDigits(int n);

in C++ which would return the number of digits in the decimal representation of the input. For example 11->2, 999->3, -1->2 etc etc.

like image 560
jjerms Avatar asked Nov 08 '09 11:11

jjerms


3 Answers

Straightforward and simple, and independent of sizeof(int):

int NumDigits(int n) {
    int digits = 0;
    if (n <= 0) {
        n = -n;
        ++digits;
    }
    while (n) {
        n /= 10;
        ++digits;
    }
    return digits;
}
like image 177
Thomas Avatar answered Sep 28 '22 09:09

Thomas


//Works for positive integers only
int DecimalLength(int n) {
    return floor(log10f(n) + 1);
}
like image 20
vava Avatar answered Sep 28 '22 10:09

vava


The fastest way is probably a binary search...

//assuming n is positive
if (n < 10000)
    if (n < 100)
        if (n < 10)
            return 1;
        else
            return 2;
    else
        if (n < 1000)
            return 3;
        else
            return 4;
 else
     //etc up to 1000000000

In this case it's about 3 comparisons regardless of input, which I suspect is much faster than a division loop or using doubles.

like image 25
Artelius Avatar answered Sep 28 '22 10:09

Artelius