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:
- Take the input number.
- Reverse the digits of the number:
- Extract the last digit using modulus (
%). - Build the reversed number by shifting its digits left (multiplication by 10).
- Remove the last digit from the original number by integer division (
/). - Repeat until all digits are processed.
- Extract the last digit using modulus (
- Compare the reversed number with the original number.
- 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:
- Initialize two variables:
number: A copy of the input number, which we will modify.reversed: To store the reversed number, initialized to 0.
- Use a loop to process all digits:
- Extract the last digit using
number % 10. - Update
reversedby multiplying it by 10 and adding the extracted digit. - Remove the last digit from
numberusing integer division (number / 10).
- Extract the last digit using
Here’s how this translates to Swift:
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:
var number = num: Creates a modifiable copy of the input number.var reversed = 0: Initializes the reversed number to 0.while number > 0: Ensures we process digits until the number becomes 0.let digit = number % 10: Extracts the last digit.reversed = reversed * 10 + digit: Adds the extracted digit to the reversed number.number /= 10: Removes the last digit by performing integer division.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:
func isPalindrome(_ num: Int) -> Bool {
return num == reverseNumber(num) // Compare original and reversed numbers
}
Explanation: This function:
- Takes an integer
numas input. - Calls the
reverseNumberfunction to reverse the number. - Uses
==to compare the original number with the reversed number. - Returns
trueif they are equal, otherwisefalse.
3 Complete Program
Combine the above functions into a complete program:
main.swift
// 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.
