6

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
Community
  • 1
  • 1
Fábio Antunes
  • 16,984
  • 18
  • 75
  • 96
  • 1
    Do you want to check if a number is a palindrome, or actually search for palindromic numbers within a much larger number? The difference is a few lines of code (if that) to many more. – user10789 Nov 23 '09 at 20:55
  • 1
    Just check if a given number is palindrome. Not search for them in a range of number, example: 1000 to 9000. – Fábio Antunes Nov 23 '09 at 21:08
  • @Fábio: I've edited the answer a touch to clarify, then. Feel free to roll it back if I've lost your meaning, but I think that edit clarifies the confusion that had iguananet (and me) wondering. – Jed Smith Nov 23 '09 at 21:11
  • 1
    Guys your amazing, thanks to all your effort i did it. – Fábio Antunes Nov 23 '09 at 21:30
  • If someone wondering. The C# code loads the numbers from a XML File and checks if each number is palindromic or not. – Fábio Antunes Nov 23 '09 at 21:52
  • possible duplicate of [How do I check if a number is a palindrome?](http://stackoverflow.com/questions/199184/how-do-i-check-if-a-number-is-a-palindrome) – TheLethalCoder Sep 15 '15 at 14:47

16 Answers16

30

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.

Jed Smith
  • 15,584
  • 8
  • 52
  • 59
  • 41
    "Since you're working in C#, I'll use very obscure-looking Python that won't help you:" Made my day. – Mercurybullet Nov 23 '09 at 20:49
  • 1
    clever - probably a little overkill but simple to understand and program. good solution. – echo Nov 23 '09 at 20:50
  • 1
    Waiting for a Brainfuck answer - this will be even more obscure :) – schnaader Nov 23 '09 at 20:50
  • 4
    Overkill? If that's overkill, what's underkill? – mqp Nov 23 '09 at 20:55
  • 1
    @mquander: People avoid string compares for some reason, when a string reversal (quick pointer walk) and string compare (quick pointer walk) outweigh creating an array and indexing into it `n / 2` times. I know string compares are efficient under the hood, and I don't fear using them; squeezing a few ms out of that tight loop at the expense of readability is a moot argument. – Jed Smith Nov 23 '09 at 20:57
  • Oh, I understand, if you meant that it's not very performant. I just misinterpreted "overkill." – mqp Nov 23 '09 at 21:11
  • @mquander: I'm taking that to be what justin meant. It's an inference, however, and I might be wrong. – Jed Smith Nov 23 '09 at 21:12
  • @mquander and Jed Smith: Yeah, i was referring to efficiency - i figure any time strings are involved (especially when ONLY strings are involved) efficiency is a worthy concern. there are ways to make this more efficient, through the type of algorithmic trickery we all know and love. that said, i'm not an efficiency bigot, and i like Jed Smith's solution. it's certainly the one I would choose. – echo Nov 24 '09 at 06:41
  • @justin: Yeah, I knew you weren't being hostile -- I gotcha. No worries. – Jed Smith Nov 24 '09 at 15:53
15

Main idea:

Input number: 12321
Splitting the digits of the number, put them into an array
=> array [1, 2, 3, 2, 1]
Check if array[x] = array[arr_length - x] for all x = 0..arr_length / 2
If check passed => palindrome
schnaader
  • 49,103
  • 10
  • 104
  • 136
4

There are many ways. Probably the simplest is to have 2 indexes, i at beginning and j at end of number. You check to see if a[i] == a[j]. If so, increment i and decrement j. You stop when i > j. When looping if you ever reach a point where a[i] != a[j], then it's not a palindrome.

dcp
  • 54,410
  • 22
  • 144
  • 164
2

Here's some working code. The first function tests if a number is palidromic by converting it to a string then an IEnumerable and testing if it is equal to its reverse. This is enough to answer your question. The main function simply iterates over the integers testing them one by one.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static bool IsPalindromic(long l)
    {
        IEnumerable<char> forwards = l.ToString().ToCharArray();
        return forwards.SequenceEqual(forwards.Reverse());
    }

    public static void Main()
    {
        long n = 0;
        while (true)
        {
            if (IsPalindromic(n))
                Console.WriteLine("" + n);
            n++;
        }
    }
}

Update: Here is a more direct method of generating palindromes. It doesn't test numbers individually, it just generates palindromes directly. It's not really useful for answering your homework, but perhaps you will find this interesting anyway:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void Main()
    {
        bool oddLength = true;
        ulong start = 1;
        while (true)
        {
            for (ulong i = start; i < start * 10; ++i)
            {
                string forwards = i.ToString();
                string reverse = new string(forwards.ToCharArray()
                                                    .Reverse()
                                                    .Skip(oddLength ? 1 : 0)
                                                    .ToArray());
                Console.WriteLine(forwards + reverse);
            }
            oddLength = !oddLength;
            if (oddLength)
                start *= 10;
        }
    }
}
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 3
    Why not? He said it would be useful, so I provided it. If he prefers to work it out for himself first, nothing is forcing him to look here. – Mark Byers Nov 23 '09 at 21:19
  • Recommend you read: http://meta.stackexchange.com/questions/10811/homework-on-stackoverflow – Jed Smith Nov 23 '09 at 21:21
  • 1
    OK, and this is the very first thing I saw: "It's irrelevant that it's homework: always just answer with complete code." So what's your point? – Mark Byers Nov 23 '09 at 21:23
  • 1
    Ah, that's just one of the "extreme" positions that he was attempting to reconcile. I still think it's his choice if he wants to look at complete code or not. – Mark Byers Nov 23 '09 at 21:26
  • Actually, that statement was an "extreme" (his words) position of some in the community at that time. You need to read the entire document: *Try to give suggestions that will lead the asker in the correct direction rather than providing a ready-made answer.* *It's usually better not to provide a complete code sample if a question looks very strongly like homework.* – Jed Smith Nov 23 '09 at 21:26
  • 1
    My opinion is that if someone comes on here asking for hints to do homework, I'll give them hints. If they want the answer, I'll give them the answer. It might be a good idea to explain to students why giving hints is better than just giving them the answer, but if they want the answer, why not give it? I find that I more agree with the second post than the first on that page. I don't think this is the place to discuss this though. It's off-topic for the question. – Mark Byers Nov 23 '09 at 21:35
  • Guys. This is not a homework. I asked someone homework in C# to start doing something in C#, and this came up. – Fábio Antunes Nov 23 '09 at 21:47
  • Fábio, I considered that angle as well -- however, the person who gave this to you got the question from somewhere, as well, and there's something to be said for leaving the answer to a homework problem in Google. Experienced SO users, in my experience, err on the side of allowing people to learn for *themselves* (as you did). This is backed up by an unofficial recommendation from a moderator on Meta. Mark went against the grain by writing your code for you, and it's a disservice to a student who is trying to learn -- though this case was loose for you -- to write code for them. – Jed Smith Nov 23 '09 at 22:02
2

My solution:

bool IsPalindrome(string str)
{
    if(str.Length == 1 || str.Length == 0) return true;
    return str[0] == str[str.Length-1] && IsPalindrome(str.Substring(1,str.Length-2));
}
Rezo Megrelidze
  • 2,877
  • 1
  • 26
  • 29
1

Here's some pseudocode:

function isPalindrome(number) returns boolean
  index = 0
  while number != 0
    array[index] = number mod 10
    number = number div 10
    index = index + 1

  startIndex = 0;
  endIndex = index - 1

  while startIndex > endIndex
    if array[endIndex] != array[startIndex]
      return false
    endIndex = endIndex - 1
    startIndex = startIndex + 1

  return true

Note that that's for base 10. Change the two 10s in the first while loop for other bases.

Moishe Lettvin
  • 8,462
  • 1
  • 26
  • 40
  • You can do this without allocating memory by eliminating the array, if you understand what the string conversion is doing. That's what I was trying to show. – Moishe Lettvin Nov 23 '09 at 21:27
1

The following function will work for both numbers as well as for strings.

public bool IsPalindrome(string stringToCheck)
{
   char[] rev = stringToCheck.Reverse().ToArray();
   return (stringToCheck.Equals(new string(rev), StringComparison.OrdinalIgnoreCase));
}

zamirsblog.blogspot.com

Zamir
  • 77
  • 3
0

in theory you want to convert the number to a string. then convet the string to an array of characters and loop the array comparing character (i) with character (array length - i) if the two characters are not equal exit the loop and return false. if it makes it all the way through the loop it is a Palindrome.

ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78
0

Interesting. I'd probably convert the number to a string, and then write a recursive function to decide whether any given string is a palendrome.

echo
  • 7,737
  • 2
  • 35
  • 33
0
 int n = check_textbox.Text.Length;
        int check = Convert.ToInt32(check_textbox.Text);
        int m = 0;
        double latest=0;
        for (int i = n - 1; i>-1; i--)
        {
                double exp = Math.Pow(10, i);
                double rem = check / exp;
                string rem_s = rem.ToString().Substring(0, 1);
                int ret_rem = Convert.ToInt32(rem_s);
                double exp2 = Math.Pow(10, m);
                double new_num = ret_rem * exp2;
                m=m+1;
                latest = latest + new_num;
                double my_value = ret_rem * exp;
                int myvalue_int = Convert.ToInt32(my_value);
                check = check - myvalue_int;
        }
        int latest_int=Convert.ToInt32(latest);
        if (latest_int == Convert.ToInt32(check_textbox.Text))
        {
            MessageBox.Show("The number is a Palindrome      number","SUCCESS",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("The number is not a Palindrome number","FAILED",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
        }
Ajai
  • 1
  • Nice answer. Please add some explanation why and how this answers the question, to make it even better. – MeanGreen Dec 01 '15 at 11:09
0
public class Main {

    public static boolean Ispalindromic(String word) {

        if (word.length() < 2) {
            return true;
        }
        else if (word.charAt(0) != word.charAt(word.length() - 1)) {
            return false;
        } else {
            Ispalindromic(word.substring(1, word.length() - 1));
        }
        return true;
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String word = sc.nextLine();
        System.out.println(Ispalindromic(word) ? "it is palidromic" : "it is not palidromic");
    }
}
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
0

This is my solution coming from a beginner:

        Console.Write("Enter a number to check if palindrome: ");
        bool palindrome = true;
        int x = int.Parse(Console.ReadLine());
        /* c is x length minus 1 because when counting the strings 
        length it starts from 1 when it should start from 0*/
        int c = x.ToString().Length - 1;
        string b = x.ToString();
        for (int i = 0; i < c; i++)
            if (b[i] != b[c - i])
                palindrome = false;
        if (palindrome == true)
            Console.Write("Yes");
        else Console.Write("No");
        Console.ReadKey();
0

You need to reverse the number then compare the result to the original number. If it matches, you have a palindrome. It should work irrespective of the number being even, odd or symmetric.

public static bool IsNumberAPalindrome(long num)
{
   return long.Parse(string.Join("", num.ToString().ToCharArray().Reverse().ToArray())) == num ? true : false;
}
1fuyouinfinite
  • 1
  • 1
  • 1
  • 14
0

The implementation is bellow:

public bool IsPalindrome(int x) {
    string test = string.Empty;
    string res = string.Empty;

    test = x.ToString();
    var reverse = test.Reverse();

    foreach (var c in reverse)
    {
        res += c.ToString();
    }

    return test == res;
}
MartenCatcher
  • 2,713
  • 8
  • 26
  • 39
Ramziii
  • 1
  • 3
0
  1. You have a string, it can have integers, it can have characters, does not matter.
  2. You convert this string to an array, depending on what types of characters the strings consist of, this may use to toCharArray method or any other related method.
  3. You then use the reverse method that .NET provides to reverse your array, now you have two arrays, the original one and the one you reversed.
  4. You then use the comparison operator (NOT THE ASSIGNMENT OPERATOR!) to check if the reversed one is the same as the original.
Neil Meyer
  • 473
  • 4
  • 15
0

something like this

bool IsPalindrome(int num)
{
    var str = num.ToString();
    var length = str.Length;
    
    for (int i = 0, j = length - 1; length/2 > i; i++, j-- ){
        if (str[i] != str[j])
            return false;
    }
    return true;
}

you could even optimise it

fs_dm
  • 391
  • 3
  • 13