Hello, today, we gonna discuss the count digit problem. Let’s start.
If you prefer watching over reading, don't worry! You can also check out my detailed video:
What is the count digit problem?
🤔I think we don’t need to explain so much math stuff, I will just show you some examples and you will be able to understand some patterns.
Pattern
Little Quiz
Answer
C: 3
But, you told me, I know how to count, but how to explain it to my computer?
Problem Statement
Given a number N, the task is to return the count of digits in this number.
The main idea is to remove digits one by one and take a count
How to remove the digits?
If you’d like to remove a digit, you should divide our number by 10. For example: If we divide 255 by 10 it gives us 25. We will remove the last digit.
How long do we remove digits?
Let’s divide our number 255 by 10 till some point.
255 divided by 10, which gives us 25.
25 divided by 10, the result is 2.
2 divided by 10, gives us 0.
And our 0
is some point when we should stop to divide our number by 10
.
Take a pause and try it
Please have a little break and did it:
Explaining of Code
Let's take number = 123
:
In the first iteration, we divide
123
by10
, which gives us12
In the second iteration, we divide
12
by 10, resulting in1
.In the third iteration, we divide
1
by10
, which gives0
.
Our time complexity will be Theta(d) - where d is the number of digits in the number.
Conclusion
If you enjoyed it make Like and Comment.