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


What Does it Mean to Reverse an Integer?

Reversing an integer means rearranging its digits in reverse order. For example:

  • The reverse of 12345 is 54321.
  • The reverse of -678 is -876.
  • The reverse of 0 is still 0.

We will use a mathematical approach to reverse the digits of an integer.


Algorithm to Reverse an Integer

To reverse an integer, follow these steps:

  1. Initialize a variable reversed to 0 to store the reversed number.
  2. Take the absolute value of the integer to handle negative numbers separately.
  3. Use a loop to process the digits:
    1. Extract the last digit using modulus operation (% 10).
    2. Append the digit to reversed by multiplying reversed by 10 and adding the digit.
    3. Remove the last digit from the number using integer division (/ 10).
  4. After the loop, restore the negative sign if the original number was negative.
  5. Return the reversed number.

This algorithm ensures that each digit is processed exactly once to reverse the number.


Step-by-Step Implementation in Swift

Let’s translate the algorithm into Swift code step by step.

1. Initialize Variables

Create a function that initializes the reversed variable and takes the absolute value of the number:

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

2. Reverse the Digits

Use a loop to reverse the digits by appending each digit to the reversed variable:

</>
Copy
func reverseInteger(_ number: Int) -> Int {
    var num = abs(number)  // Take the absolute value of the number
    var reversed = 0       // Initialize the reversed number to 0
    
    while num > 0 {
        let digit = num % 10       // Extract the last digit
        reversed = reversed * 10 + digit // Append the digit to reversed
        num /= 10                  // Remove the last digit
    }
    return reversed // Placeholder for restoring the sign
}

3. Handle Negative Numbers

Restore the negative sign if the original number was negative:

</>
Copy
func reverseInteger(_ number: Int) -> Int {
    var num = abs(number)  // Take the absolute value of the number
    var reversed = 0       // Initialize the reversed number to 0
    
    while num > 0 {
        let digit = num % 10       // Extract the last digit
        reversed = reversed * 10 + digit // Append the digit to reversed
        num /= 10                  // Remove the last digit
    }
    
    return number < 0 ? -reversed : reversed // Restore the sign if negative
}

Explanation:

var num = abs(number): Handles negative numbers by taking the absolute value.

let digit = num % 10: Extracts the last digit of the number.

reversed = reversed * 10 + digit: Appends the digit to the reversed number.

num /= 10: Removes the last digit from the number.

return number < 0 ? -reversed : reversed: Restores the negative sign if the input was negative.

4. Test the Function

Let’s test the function with some example inputs:

</>
Copy
// Test cases
print("Reversed 12345: \(reverseInteger(12345))")  // 54321
print("Reversed -678: \(reverseInteger(-678))")   // -876
print("Reversed 0: \(reverseInteger(0))")         // 0

The function correctly reverses the digits of positive, negative, and zero values.


Complete Swift Program

Here’s the complete Swift program:

</>
Copy
import Foundation

// Function to reverse an integer
func reverseInteger(_ number: Int) -> Int {
    var num = abs(number)  // Take the absolute value of the number
    var reversed = 0       // Initialize the reversed number to 0
    
    while num > 0 {
        let digit = num % 10       // Extract the last digit
        reversed = reversed * 10 + digit // Append the digit to reversed
        num /= 10                  // Remove the last digit
    }
    
    return number < 0 ? -reversed : reversed // Restore the sign if negative
}

// Test cases
print("Reversed 12345: \(reverseInteger(12345))")  // 54321
print("Reversed -678: \(reverseInteger(-678))")   // -876
print("Reversed 0: \(reverseInteger(0))")         // 0

Output

</>
Copy
Reversed 12345: 54321
Reversed -678: -876
Reversed 0: 0

Screenshot from Xcode

Swift Program to Reverse an Integer