Count digits
- Shreyas Naphad
- May 8, 2024
- 1 min read
Updated: Jun 5, 2024
In programming, counting the number of digits in an integer is a very common problem that is asked to solve. There are several problems in which this technique of counting digits comes in handy. So, in this article, we will learn how to count the number of digits of an integer.
Problem Statement: Given an integer N, write a program to count the number of digits present in N.
So we will be looking at 2 simple solutions using C++ that would help us to solve this problem easily.
Solution 1:
Explanation:
· Variable x contains our integer and variable count is used to count the number of digits present in the integer.
· Now while x!=0, we will divide x by 10 so the last digit will be eliminated and the count will be incremented by 1 as now we know that there was 1 digit already present that just got eliminated
· Once x becomes 0 this means that all digits have been eliminated and now count will have the answer.
Solution 2:
Explanation:
· Here we simply convert the integer into a string data type.
· We then count the length of this string which is equivalent to counting the number of digits of an integer and that is our answer.
コメント