0

How can i know the length of an integer?

suppose an integer i=124682; how can i know that how many digits this integer has?

8th May 2020, 10:30 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
3 Answers
+ 1
i would do this: int digits, num = 124682; for (digits = 0; num; digits++) num /= 10; cout << digits << '\n';
8th May 2020, 10:32 AM
Gen2oo
Gen2oo - avatar
+ 1
// my one-liner to count digits using a mathematical approach #include <math.h> . . . int i = 124682, nDigits; nDigits = floor(log10(abs(i == 0 ? 1 : i))) + 1; The code is unreadable and relies on a mathematical "trick", so I don't strongly recommend this approach. Here is sample code that uses it: https://code.sololearn.com/c3EwDn9O4Gbg/?ref=app
9th May 2020, 12:07 AM
Brian
Brian - avatar