Sure it's possible, something like (for 32-bit numbers):
int numDigitsU (unsigned int n) {
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
/* 4294967295 is 2^32-1 - add more ifs as needed
and adjust this final return as well. */
return 10;
}
The signed variant is a little trickier since the sign is reversed first, and you have to watch out for MININT
:
int numDigitsS (int n) {
if (n == MININT) n = MAXINT; // same number of digits, usually.
if (n < 0) n = -n; // reverse sign.
return numDigitsU (n); // call the unsigned variant.
}
Just adjust the highest comparison value and return value based on the size of your largest unsigned int
.
This should work with all allowed negative codings: two's complement, ones' complement, and sign/magnitude.