I have 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 challenge is not using any loops or recursion, just an if
statement.
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 the log function.
cplusplus - log10
cplusplus - std::abs
Easy way although somewhat expensive, turn your number to string and take its size like the example 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
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