
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Number of Digits in an Integer using Kotlin
In this article, we will understand how to count the number of digits in an integer. The digits in an integer are counted using a loop and a counter.
Below is a demonstration of the same ?
Suppose our input is ?
Number : 15161718
The desired output would be ?
The result is : 8
Algorithm
Step 1 ? START
Step 2 ? Declare two integer values namely count and myInput.
Step 3 ? Define the values
Step 4 ? Using a while loop, divide the input value by 10 until the number is reduced to its lowest possible value. Increment the counter value each time.
Step 5 ? Display the counter value as result
Step 6 ? Stop
Example 1
In this example, we will count the number of digits in an Integer. First, declare and initialize two variables, one for count and another our input i.e., the input for which we want to count the number of digits ?
var count = 0 var myInput = 15161718
Then, count the number of digits in the input using a while loop ?
while (myInput != 0) { myInput /= 10 ++count }
Let us now see the complete example to count the number of digits in an integer ?
fun main() { var count = 0 var myInput = 15161718 println("The number is defined as $myInput") while (myInput != 0) { myInput /= 10 ++count } println("Number of digits: $count") }
Output
The number is defined as 15161718 Number of digits: 8
Example 2
In this example, we will count the Number of Digits in an Integer ?
fun main() { var myInput = 15161718 println("The number is defined as $myInput") countDigits(myInput) } fun countDigits(input: Int) { var myInput = input var count = 0 while (myInput != 0) { myInput /= 10 ++count } println("Number of digits: $count") }
Output
The number is defined as 15161718 Number of digits: 8