I have an integer and need to find out how many digits are in it.
For positive numbers, use log10:
int a = 1234;
int len = static_cast<int>(log10(a)+1.);
If you need to be thorough:
int length(int a)
{
int b = abs(a);
if (b == 0) return 1;
return static_cast<int>(log10(b)+1.);
}
With that said, it would be a better choice to do repeated division by 10 in practice.
int length(int a)
{
int b = 0;
for (a = abs(a); a != 0; b++, a /= 10) continue;
return b;
}
You probably mean you have a string containing numbers rather than an int in python:
>>> i = 123456789
>>> len(i)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(str(i))
9
If this is also the case in c++ it's easy to find the length of a string using:
my_str_value.length()
or for a C string using strlen
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With