- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Here we will see how to check how many digits are there in an integer in C++. At first we will see the traditional rule, then see one short method to find.

In the first method, we will reduce the number using dividing it by 10. And count until the number reaches to 0.

#include <iostream> using namespace std; int count_digit(int number) { int count = 0; while(number != 0) { number = number / 10; count++; } return count; } int main() { cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl; }

Number of digits in 1245: 4

Now, we will see the shorter method. In this method we will use the log base 10 function to get the result. The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

#include <iostream> #include <cmath> using namespace std; int count_digit(int number) { return int(log10(number) + 1); } int main() { cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl; }

Number of digits in 1245: 4

- Related Questions & Answers
- How many keywords are there in C++?
- How many locking systems are there in JDBC?
- How many non-access modifiers are there in Java?
- How many types of inheritance are there in Python?
- How many types of constructors are there in Java?
- How many different types of eclipses are there?
- How many types of JDBC Drivers are there?
- How many ways are there to convert an Array to ArrayList in Java?
- How many ways are there to register a driver in Java?
- How many types of Result Sets are there in JDBC What are they?
- Count even and odd digits in an Integer in C++
- C++ program to Zoom digits of an integer
- How many packages and classes are there in Java Standard Edition 8?
- How many ways are there to initialize a final variable in java?
- Subtract the Product and Sum of Digits of an Integer in C++

Advertisements