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?
3 ответов
+ 1
i would do this:
int digits, num = 124682;
for (digits = 0; num; digits++)
num /= 10;
cout << digits << '\n';
+ 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