Swift – Count the Number of Digits in an Integer

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


What Does it Mean to Count Digits?

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

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

To solve this, we can use either a mathematical approach or convert the number to a string and count its characters.


Algorithm to Count Digits

We will use a mathematical approach to count the digits:

  1. Take the absolute value of the number (to ignore the sign).
  2. Initialize a counter to 0.
  3. Use a loop to repeatedly divide the number by 10:
    1. Increment the counter on each iteration.
    2. Stop when the number becomes 0.
  4. Return the value of the counter as the number of digits.

This algorithm ensures that every digit in the number is processed exactly once.


Step-by-Step Implementation in Swift

Let’s implement the algorithm in Swift step by step.

1. Handle Negative Numbers

Write a function that takes an integer and uses the absolute value to handle negative numbers:

</>
Copy
func countDigits(_ number: Int) -> Int {
    var num = abs(number) // Take the absolute value
    return 0 // Placeholder for further steps
}

2. Count Digits Using a Loop

Extend the function to use a loop that repeatedly divides the number by 10 and increments a counter:

</>
Copy
func countDigits(_ number: Int) -> Int {
    var num = abs(number) // Take the absolute value
    var count = 0         // Initialize the counter
    
    repeat {
        count += 1        // Increment the counter
        num /= 10         // Remove the last digit
    } while num > 0       // Continue until the number becomes 0
    
    return count // Return the total count
}

Explanation:

  • var num = abs(number): Handles negative numbers by taking the absolute value.
  • var count = 0: Initializes the counter to 0.
  • repeat: Ensures the loop runs at least once (to handle the number 0 correctly).
  • count += 1: Increments the counter for each digit.
  • num /= 10: Removes the last digit by integer division.
  • return count: Returns the final count after the loop ends.

3. Test the Function

Let’s test the function with some example inputs:

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

The function calculates the number of digits for both positive and negative numbers, as well as for zero.


Complete Swift Program

Here’s the complete Swift program to count the number of digits in a given integer.

main.swift

</>
Copy
import Foundation

// Function to count the number of digits in an integer
func countDigits(_ number: Int) -> Int {
    var num = abs(number) // Take the absolute value
    var count = 0         // Initialize the counter
    
    repeat {
        count += 1        // Increment the counter
        num /= 10         // Remove the last digit
    } while num > 0       // Continue until the number becomes 0
    
    return count // Return the total count
}

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

Output

</>
Copy
Number of digits in 12345: 5
Number of digits in -678: 3
Number of digits in 0: 1

Screenshot from Xcode

Swift Program to Count the Number of Digits in an Integer