Find Number of Digits in Number
1 min readNov 18, 2021
Count the number of digits in a long integer entered by a user.
Right off the bat, we know we’re going to have to iterate over the number to count the number of digits. So let’s start by setting a variable, and then initializing a while loop. We can only count the digits when the test expression is not equal to zero.
function countDigit(n) { let count = 0; while (n != 0)
}
Within the while loop, we’ll use a handy JavaScript function that will make things easier for us. Math.floor returns the largest integer less than or equal to a given number.
function countDigit(n) { let count = 0; while (n != 0)
{
n = Math.floor(n / 10);
}
}
We will increase our count variable through each iteration, until n equals 0, which is how we break out the loop.
function countDigit(n) { let count = 0; while (n != 0) { n = Math.floor(n / 10); ++count; } return count;}
Lastly, return the count. Happy coding!