1

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 :)

Liam George Betsworth
  • 18,373
  • 5
  • 39
  • 42
user1440323
  • 23
  • 1
  • 2
  • 4
  • 2
    Yes, in this case `Convert.ToBoolean(num)` is just an overcomplicated (and imvho overly confusing and obfuscating way) of writing `while(num > 0)`. – Niels Keurentjes May 13 '13 at 10:05
  • Just Realized that the other snippet did not come out right so here it is: int num, rem, sum = 0, temp; Console.Write("\n Enter a number: "); num = Convert.ToInt32(Console.ReadLine()); temp = num; while (Convert.ToBoolean(num)) { rem = num % 10; num = num / 10; sum = sum * 10 + rem;} Console.WriteLine("\n The Reversed Number is: {0} \n", sum); if (temp == sum) {Console.WriteLine("\n Number is Palindrome \n\n");} else{Console.WriteLine("\n Number is not a palindrome \n\n");} – user1440323 May 13 '13 at 10:05
  • 3
    Why not just convert it into a string and check if the string is a palindrome. See this thread : http://stackoverflow.com/questions/199184/how-do-i-check-if-a-number-is-a-palindrome – cvraman May 13 '13 at 10:06
  • @Niels to be exact: `while(num != 0)` – Eren Ersönmez May 13 '13 at 10:07
  • Thanks a lot Niels but for the First piece of code is there a work around or is that just badly written code? – user1440323 May 13 '13 at 10:13
  • @ErenErsönmez since a negative number can't be a palindrome by definition the result is by definition identical. – Niels Keurentjes May 13 '13 at 10:13
  • @user1440323 just store it in a temp variable like the second sample does. – Niels Keurentjes May 13 '13 at 10:14
  • +1 to "convert it to a string and check that instead". Reversing a string is an easy operation (a quick google brings up many easy methods) and then you can just do a quick comparison of equality. – FakeDIY May 13 '13 at 10:18

6 Answers6

4

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).

Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86
  • @user1440323 If this has answered your question, you should mark it as the answer with the tick on the left... – El Ronnoco May 13 '13 at 16:00
2
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...

El Ronnoco
  • 11,753
  • 5
  • 38
  • 65
2

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)

dognose
  • 20,360
  • 9
  • 61
  • 107
0

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..

Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0
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..

Ultima
  • 31
  • 5
-1

Use the following code:

public boolean isPalindrom(Integer number)
{ 
   return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}
László Papp
  • 51,870
  • 39
  • 111
  • 135