Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting digits using while loop

I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:

int x;    
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
  count++;
  x = x/10;
}

From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.

Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?

like image 828
E.O. Avatar asked Jul 06 '11 19:07

E.O.


People also ask

How do you count digits?

To count number of digits divide the given number by 10 till number is greater than 0. For each iteration increment the value of some count variable. Step by step descriptive logic to count number of digits in given integer using loop.

How do you count the number of digits without a loop?

Now, we will see how to count the number of digits without using a loop. We can also count the number of digits with the help of the logarithmic function. The number of digits can be calculated by using log10(num)+1, where log10() is the predefined function in math.

How do you count the number of digits in a string?

isDigit(s. charAt(i)) will count the number of digits in the given string. 'Character. isDigit' will count the number of each digit in the string.


2 Answers

In your particular example you could read the number as a string and count the number of characters.

But for the general case, you can do it your way or you can use a base-10 logarithm.

Here is the logarithm example:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double n;
    cout << "Enter a number: ";
    cin >> n;

    cout << "Log 10 is " << log10(n) << endl;
    cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
    return 0;
}
like image 76
Zan Lynx Avatar answered Sep 18 '22 17:09

Zan Lynx


int count = (x == 0) ? 1 : (int)(std::log10(std::abs((double)(x)))))) + 1;
like image 27
David Hammen Avatar answered Sep 17 '22 17:09

David Hammen