Count the Number of Digits present in a Number in Go
In this tutorial, we will learn how to count the number of digits present in a number in Go. We will cover the basic concept of number manipulation and implement a function to perform the counting.
What is Number Manipulation
Number manipulation involves performing operations on numbers to achieve a specific result. Counting the number of digits in a number is a common task in number manipulation.
Syntax
The syntax to count the number of digits in a number in Go is:
func countDigits(n int) int {
count := 0
if n == 0 {
return 1
}
for n != 0 {
n /= 10
count++
}
return count
}Example 1: Counting the number of digits in a number
We can create a function to count the number of digits in a given number by repeatedly dividing it by 10 and keeping a count of the iterations.
For example,
- Define a function named
countDigitsthat takes one parameternof typeint. - Initialize a variable
countto 0 to store the count of digits. - Check if
nis 0. If true, return 1. - Use a
forloop to iterate whilenis not 0. - In each iteration, divide
nby 10 and increment thecountvariable. - Return the
countvariable. - In the main function, call the
countDigitsfunction with a sample number and print the result.
Go Program
package main
import (
"fmt"
)
func countDigits(n int) int {
count := 0
if n == 0 {
return 1
}
for n != 0 {
n /= 10
count++
}
return count
}
func main() {
// Sample number
number := 12345
// Count the number of digits
result := countDigits(number)
// Print the result
fmt.Printf("Number of digits in %d is %d\n", number, result)
}Output
Number of digits in 12345 is 5