Swift – Palindrome Program

In this tutorial, we will learn how to check if a number is a palindrome in Swift. We’ll cover what a palindrome is, the algorithm to determine if a number is a palindrome, and step-by-step implementation in Swift with the final program and output.


What is a Palindrome?

A palindrome is a number or string that reads the same backward as forward. For example, the numbers 121, 1221, and 12321 are palindromes, while 123 and 4567 are not. This property makes it an interesting problem to solve algorithmically and programmatically.


Algorithm to Check if a Number is a Palindrome

Let’s break down the problem into an algorithm:

  1. Take the input number.
  2. Reverse the digits of the number:
    1. Extract the last digit using modulus (%).
    2. Build the reversed number by shifting its digits left (multiplication by 10).
    3. Remove the last digit from the original number by integer division (/).
    4. Repeat until all digits are processed.
  3. Compare the reversed number with the original number.
  4. If they are the same, the number is a palindrome; otherwise, it is not.

Each of these steps will be implemented as program statements in Swift.


Step-by-Step Implementation in Swift

Let’s convert the algorithm into Swift code by implementing one step at a time.

1. Reverse the Digits of a Number

To reverse the digits of a number, follow these steps:

  1. Initialize two variables:
    1. number: A copy of the input number, which we will modify.
    2. reversed: To store the reversed number, initialized to 0.
  2. Use a loop to process all digits:
    1. Extract the last digit using number % 10.
    2. Update reversed by multiplying it by 10 and adding the extracted digit.
    3. Remove the last digit from number using integer division (number / 10).

Here’s how this translates to Swift:

</>
Copy
func reverseNumber(_ num: Int) -> Int {
    var number = num   // Copy of the input number
    var reversed = 0   // Initialize reversed number to 0
    
    while number > 0 { // Process all digits
        let digit = number % 10      // Extract the last digit
        reversed = reversed * 10 + digit // Add the digit to reversed number
        number /= 10                 // Remove the last digit
    }
    
    return reversed  // Return the reversed number
}

Explanation: Each line in this function corresponds to a step in the algorithm:

  1. var number = num: Creates a modifiable copy of the input number.
  2. var reversed = 0: Initializes the reversed number to 0.
  3. while number > 0: Ensures we process digits until the number becomes 0.
  4. let digit = number % 10: Extracts the last digit.
  5. reversed = reversed * 10 + digit: Adds the extracted digit to the reversed number.
  6. number /= 10: Removes the last digit by performing integer division.
  7. return reversed: Returns the fully reversed number.

2. Compare the Original and Reversed Numbers

Next, write a function to check if the original number is equal to the reversed number. If they match, the number is a palindrome:

</>
Copy
func isPalindrome(_ num: Int) -> Bool {
    return num == reverseNumber(num) // Compare original and reversed numbers
}

Explanation: This function:

  1. Takes an integer num as input.
  2. Calls the reverseNumber function to reverse the number.
  3. Uses == to compare the original number with the reversed number.
  4. Returns true if they are equal, otherwise false.

3. Complete Program

Combine the above functions into a complete program:

main.swift

</>
Copy
// Function to reverse a number
func reverseNumber(_ num: Int) -> Int {
    var number = num
    var reversed = 0
    
    while number > 0 {
        let digit = number % 10
        reversed = reversed * 10 + digit
        number /= 10
    }
    
    return reversed
}

// Function to check if a number is a palindrome
func isPalindrome(_ num: Int) -> Bool {
    return num == reverseNumber(num)
}

// Main program
let number = 121
if isPalindrome(number) {
    print("\(number) is a palindrome.")
} else {
    print("\(number) is not a palindrome.")
}

let anotherNumber = 123
if isPalindrome(anotherNumber) {
    print("\(anotherNumber) is a palindrome.")
} else {
    print("\(anotherNumber) is not a palindrome.")
}

Output

121 is a palindrome.
123 is not a palindrome.