I'm trying to determinate the amount of digits in integer in C++ and so far I've tried the following methods:
1.
unsigned GetNumberOfDigits (unsigned i)
{
return i > 0 ? (int) log10 ((double) i) + 1 : 1;
}
2.
int length_of_int(int input){
int length = 0;
while(input > 0){
length++;
input /= 10;
if(input == 0)
length++;
}
return length;
}
3.
int NumDigits(int x)
{
x = abs(x);
return (x < 10 ? 1 :
(x < 100 ? 2 :
(x < 1000 ? 3 :
(x < 10000 ? 4 :
(x < 100000 ? 5 :
(x < 1000000 ? 6 :
(x < 10000000 ? 7 :
(x < 100000000 ? 8 :
(x < 1000000000 ? 9 :
10)))))))));
}
And none works in my case, such as "000101" it has 6 digits, but it either says 4 or 3. Any help?
The purpose of this is checking a valid date, in format YYMMDD. I am aware that this type of format has Y2K-error but it's specified in the task it has to be that one.
You wrote And none works in my case, such as "000101" it has 6 digits, but it either says 4 or 3. Any help?
if the integer was 000101 then the first 3 zeros would get removed, it would become 101.
If it was a string you just count how much letters in the string.
Seems you want to represent binary I would use bit array for this
Edit: Okay it's not binary it's a date which should be stored into string to avoid this Y2K bug.
int count = strlen("000101");