Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count digits of number without loop C++

Tags:

c++

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?

like image 643
yael aviv Avatar asked Sep 08 '14 09:09

yael aviv


2 Answers

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

like image 193
Vladp Avatar answered Sep 23 '22 17:09

Vladp


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

like image 45
101010 Avatar answered Sep 22 '22 17:09

101010