I need to count the number of digits in a number.
I divide the number to 10 until I get 0. Each iteration increments the counter.
int num; cin>>num; while(num > 0) { counter++; num = num / 10; }
The problem is not using loops or recursion, but simply the expression if.
if
Is it possible?
counter = log (num) / log (10)
in C ++:
#include <cmath> .... counter = num == 0 ? 1 : log10(std::abs(num)) + 1;
what you want is a log feature.
cplusplus - log10
cplusplus - std :: abs
An easy way, albeit somewhat expensive, turn your number into a string and take its size, as shown below:
#include <iostream> #include <string> int main() { int i = 1232323223; std::string str = std::to_string(std::abs(i)); std::cout << "Number of Digits: " << str.size() <<std::endl; }
LIVE DEMO
- sprintf, :
sprintf
int digits(int n) { char s[32]; int len = sprintf(s, "%d", n); if (n < 0) len--; // NB: handle negative case return len; }
, , - ( 32- ):
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; }
, , MININT:
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. }
unsigned int.
unsigned int
: , /.
, , int . , 10, 100, 1000 .. .
int
int num = abs(number); if (num < 10000) { if (num < 100) return num < 10 ? 1:2; else return num < 1000 ? 3:4; } else { ... }