user1440323
user1440323

Reputation: 33

Finding out whether a number is a palindrome or not in C#

I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.

After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. How can I rectify this??

My Code

        int i, remainder = 0, newnum = 0;
        Console.WriteLine("Enter a Number: ");
        int uinput = Convert.ToInt32((Console.ReadLine()));
        for (i = uinput; i > 0; i = (i / 10))
        {
            remainder = i % 10;
            Console.Write(remainder);

            newnum = remainder;

        }


        if (newnum == uinput)
        {
            Console.WriteLine("The Number {0} is a palindrome", uinput);
        }
        else
        {
            Console.WriteLine("Number is not a palidrome");
        }
        Console.WriteLine(uinput);
        Console.WriteLine(newnum);
        Console.ReadKey();
    }

I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?

The Code reffered to above

        int num, rem, sum = 0, temp;
        //clrscr();
        Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
        Console.Write("\n Enter a number: ");
        num = Convert.ToInt32(Console.ReadLine());
        temp = num;
        while (Convert.ToBoolean(num))
        {
            rem = num % 10;  //for getting remainder by dividing with 10
            num = num / 10; //for getting quotient by dividing with 10
            sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
                       remainder*/
        }
        Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
        if (temp == sum) //checking whether the reversed number is equal to entered number
        {
            Console.WriteLine("\n Number is Palindrome \n\n");
        }
        else
        {
            Console.WriteLine("\n Number is not a palindrome \n\n");
        }
        Console.ReadLine();

Any sort of help is much appreciated!! Thank You :)

Upvotes: 1

Views: 23487

Answers (6)

dognose
dognose

Reputation: 20909

Easiest way:

public static Boolean isPalindrom(Int32 number){
  char[] n1 = number.ToString().ToCharArray();
  char[] n2 = number.ToString().ToCharArray();
  Array.Reverse(n2);

  String s1 = new String(n1);
  String s2 = new String(n2);

  return (s1 == s2);
}

https://dotnetfiddle.net/HQduT5

you could also use Integers for s1 and s2 and return (s1-s2 == 0)

Upvotes: 2

user3198059
user3198059

Reputation: 1

Use the following code:

public boolean isPalindrom(Integer number)
{ 
   return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}

Upvotes: -1

El Ronnoco
El Ronnoco

Reputation: 11912

public bool isPalindome(int num)
{
  string sNum = num.ToString();
  for (int i = 0; i<sNum.Length; i++) 
      if (sNum[i] != sNum[sNum.Length-1-i]) return false;

  return true;
}

I think that will do it... Untested!!

As dognose (and Eren) correctly assert you only need to go halfway through

public bool isPalindome(int num)
{
  string sNum = num.ToString();
  for (int i = 0; i < sNum.Length/2; i++) 
      if (sNum[i] != sNum[sNum.Length-1-i]) return false;

  return true;
}

You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...

Upvotes: 2

Ultima
Ultima

Reputation: 31

int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
    {
        int temp=x%10;
        ar[i]=temp;
        x=x/10;
        i++;
    }
for(int j=0, j<i,j++)
    {
        temp2=temp2*10+ar[j];
    }
if(temp2==x){cout<<"palindrome"}
    else {"not palindrome"}

ok here is the logic:

we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..

Upvotes: 0

Paolo Falabella
Paolo Falabella

Reputation: 25854

I'm not sure what you're asking, since the second snippet of code you found online should fix your issue. Your code works, if you just change the line

newnum = remainder;

to

newnum = (newnum*10) + remainder;

The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.

To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.

Try to follow it step by step with pen and paper (or with a debugger).

Upvotes: 4

Orel Eraki
Orel Eraki

Reputation: 12196

You have many ways of accomplish this exercise.

A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)

B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.

C. there are much more ways without using the string solutions, just with calculation..

Upvotes: 0

Related Questions