Checking for Palindrome Numbers in C#: An Efficient Algorithm
Learn how to check if a number is a palindrome (reads the same forwards and backward) in C#. This tutorial provides a C# program that implements a palindrome-checking algorithm, explains its logic, and demonstrates a common programming task useful in various number manipulation and algorithm implementations.
Checking for Palindrome Numbers in C#
What is a Palindrome Number?
A palindrome number is a number that remains the same when its digits are reversed. For example, 121, 131, 454, and 1001 are palindrome numbers because they read the same forwards and backward. Let's check if a number is a palindrome or not.
Palindrome Number Algorithm
- Get the number from the user as input.
- Store the original number in a temporary variable.
- Reverse the number using arithmetic operations (extracting digits and building the reversed number).
- Compare the original number (stored in the temporary variable) with the reversed number.
- If they're the same, it's a palindrome; otherwise, it's not.
C# Palindrome Program
This C# program implements the algorithm described above. It takes an integer as input from the user, reverses it, and then compares the original and reversed numbers to determine if it's a palindrome.
C# Code
using System;
public class PalindromeChecker {
public static void Main(string[] args) {
Console.Write("Enter an integer: ");
int number = int.Parse(Console.ReadLine());
if (IsPalindrome(number)) {
Console.WriteLine($"{number} is a palindrome.");
} else {
Console.WriteLine($"{number} is not a palindrome.");
}
}
public static bool IsPalindrome(int number) {
int originalNumber = number;
int reversedNumber = 0;
while (number > 0) {
int remainder = number % 10;
reversedNumber = (reversedNumber * 10) + remainder;
number /= 10;
}
return originalNumber == reversedNumber;
}
}
Conclusion
This program effectively checks for palindrome numbers in C#. The `IsPalindrome` function uses simple arithmetic operations to reverse the number and then compares it with the original. Error handling (e.g., for non-integer input) is not included in this simplified example but would be important in a production application.