My issue
please help me understand the problem
My code
#include <iostream>
using namespace std;
int main() {
int num, count = 0;
cin >> num;
while (num != 0) {
// Update your code below this line
num = num/10;
count ++;
}
cout << count;
return 0;
}
Learning course: Complete C++ course
Problem Link: Coding problem - 3 Practice Problem in Complete C++ course - CodeChef
So friend
We are trying to count the number of digits of a number.
For example
let the number be
609
every time we divide a number by 10 it gets rid of the last integer
you may think
(609 / 10) is 60.9
but we are considering integer data type.
So, the default division is floor division.
you can find this by running this code
int a = 609;
int b = 609/10;
cout << b << endl;
Now to count the number of digits
we see how many time the number can withstand division by 10.
while being greater than zero.
Lets see in action
int count=0;
while(n>0){ //609 is greater than 0
n = n/10; // n now holds 60
count++; // count now holds 1
}
again …
while(n>0){ //60 is greater than 0
n = n/10; // n now holds 6
count++; // count now holds 2
}
again …
while(n>0){ //6 is greater than 0
n = n/10; // n now holds 0
count++; // count now holds 3
}
now n becomes 0. so, we break out of the loop.
As you can see,
count variable now holds 3 that is the number of digits in 609.
Hoping I could be of help. Have a great day.