Swift – Count Number of Digits in an Integer using Recursion

In this tutorial, we will learn how to count the number of digits in an integer using recursion in Swift. We will understand the concept, write an algorithm, and implement the solution step by step with a complete Swift program and output.


Understanding the Problem

Counting the digits of an integer involves determining how many numerical digits are present in the number. For example:

  • The number 12345 has 5 digits.
  • The number -678 has 3 digits (ignoring the sign).
  • The number 0 has 1 digit.

We can solve this problem recursively by reducing the number by dividing it by 10 and counting the steps until the number becomes 0.


Algorithm to Count Digits Using Recursion

  1. Take the number as input.
  2. Base Case: If the number is 0, return 1.
  3. Recursive Case:
    1. Divide the number by 10 to remove the last digit.
    2. Call the function recursively for the reduced number.
    3. Add 1 to the result for each recursive call.

This algorithm ensures that the problem is divided into smaller subproblems until it reaches the base case.


Step-by-Step Implementation in Swift

1. Handle Base Case

Create a function that handles the base case where the number is 0 and returns 1:

</>
Copy
func countDigits(_ number: Int) -> Int {
    if number == 0 {
        return 1 // Base case: A single digit (0) has 1 digit
    }
    return 0 // Placeholder for recursive case
}

2. Add Recursive Case

Add logic to recursively divide the number by 10 and count the digits:

</>
Copy
func countDigits(_ number: Int) -> Int {
    if number == 0 {
        return 1 // Base case
    }
    return 1 + countDigits(number / 10) // Recursive case
}

Explanation:

  • if number == 0: Stops the recursion when the number becomes 0, returning 1 for the last digit.
  • 1 + countDigits(number / 10): Reduces the number by dividing it by 10 and adds 1 to the result of the recursive call.

3. Handle Negative Numbers

To handle negative numbers, take the absolute value of the input:

</>
Copy
func countDigits(_ number: Int) -> Int {
    let num = abs(number) // Handle negative numbers
    if num == 0 {
        return 1 // Base case
    }
    return 1 + countDigits(num / 10) // Recursive case
}

Explanation: Using abs(number), we ensure that the function processes the magnitude of the number, ignoring the sign.

4. Test the Function

Let’s test the function with some example inputs:

</>
Copy
// Test cases
print("Number of digits in 12345: \(countDigits(12345))") // Output: 5
print("Number of digits in -678: \(countDigits(-678))")   // Output: 3
print("Number of digits in 0: \(countDigits(0))")         // Output: 1

Complete Swift Program

Here’s the complete Swift program to count the number of digits in an integer using recursion:

</>
Copy
import Foundation

// Recursive function to count the number of digits in an integer
func countDigits(_ number: Int) -> Int {
    let num = abs(number) // Handle negative numbers
    if num == 0 {
        return 1 // Base case
    }
    return 1 + countDigits(num / 10) // Recursive case
}

// Test cases
print("Number of digits in 12345: \(countDigits(12345))") // Output: 5
print("Number of digits in -678: \(countDigits(-678))")   // Output: 3
print("Number of digits in 0: \(countDigits(0))")         // Output: 1

Output:

Number of digits in 12345: 6
Number of digits in -678: 4
Number of digits in 0: 1
Program ended with exit code: 0

Xcode Screenshot

Swift Program to Count Number of Digits in an Integer using Recursion