Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically check if a number is a palindrome

Tags:

c#

This sounds like homework, yes it is (of someone else), I asked a friend of mine who is learning C# to lend me some of his class exercises to get the hang of it.

So as the title says: How can I check if a number is a Palindrome?

I'm not asking for source code (although its very useful), but rather that someone explained how should the code should work, so that it can be applied to many different languages.


The Solution:

@statikfx searched SO for this and found the solution.

 n = num;
 while (num > 0)
 {
      dig = num % 10;
      rev = rev * 10 + dig;
      num = num / 10;
 }
// If (n == rev) then num is a palindrome
like image 998
Fábio Antunes Avatar asked Nov 23 '09 20:11

Fábio Antunes


1 Answers

I check for palindromes by converting the integer to a string, then reversing the string, then comparing equality. This will be the best approach for you since you're just starting out.

Since you're working in C# and this is homework, I'll use very obscure-looking Python that won't help you:

def is_palindrome(i):
    s = str(i)
    return s[::-1] == s

Convert that to C# and you'll have your answer.

like image 200
Jed Smith Avatar answered Oct 12 '22 23:10

Jed Smith