swift

Reverse Digits in Swift()

Parameters: num: Int

An integer to be reversed

Returns: Reversed integer provided as input

The function takes an integer and reverses its digits. For example, the input 12345 will return 54321. It can handle both positive and negative integers.

variables
while loop
division
modulus operator
conditional statements
Medium dificulty

Creating a Reverse Digit Function in Swift

Hello, fellow programmer. Welcome to this post. Together, we will explore how to code a function in Swift that reverses the digits of a number, step by step. This will provide you with a concrete example of a commonly used coding task and expand your knowledge of Swift. Ready to dive in? Let's code!

Step 1: Understand the Problem

First, we need to understand what reversing a number means. This means taking a number like 123 and changing it to 321. Essentially, we are flipping the order of the digits.

Step 2: Sketch a Plan

The Swift language does not allow us to directly reverse an integer, so we need to convert it into a string first. Once our number is a string, we can use the reversed() function to flip the digits. After that, we'll need to convert it back to integer.

Here's our initial function layout:

func reverseDigits(n: Int) -> Int {
    // Convert integer to string
    
    // Reverse the string
    
    // Convert string back to integer
    
    return 0    
}

Step 3: Convert Integer to String

You can convert an integer to a string in Swift using the String() initializer.

Here's how we add this to our function:

func reverseDigits(n: Int) -> Int {
    let stringNum = String(n)
    return 0
}

Step 4: Reverse the String

To reverse our string, we can use the reversed() function in Swift. We'll also need to convert our reversed string back to a new string.

Here's how we add this:

func reverseDigits(n: Int) -> Int {
    let stringNum = String(n)
    let reversedNum = String(stringNum.reversed())
    return 0
}

Step 5: Convert String Back to Integer

Finally, we need to convert our string back to an integer. Let's use the Int() initializer for this.

Here is the final solution.

func reverseDigits(n: Int) -> Int {
    let stringNum = String(n)
    let reversedNum = String(stringNum.reversed())
    return Int(reversedNum) ?? 0
}

Learn function in:

Reverse a number

Reverse the digits of a number

Learn more

Mathematical principle

The function exploits the mathematical properties of division and modulations. In short, `number % 10` gives us the last digit of the number and `number /= 10` removes the last digit from the number. This sequential operation is done inside a loop until `number` becomes zero, all the while accumulating the reversed number.

Learn more