C# how to check for a palindrome number

I tried to solve this problem: check if the number is a palindrome, I know that there are a lot of examples on the Internet, but I don’t understand why my code isn’t working.

using System;
class HelloWorld {
    static void Main() {
        int number = 122;
        int reverse = 0;
        while(number!=0){
            reverse = (reverse*10) + number%10;
            number/=10;
        }
        Console.Write(reverse);
        if(number==reverse){
            Console.WriteLine("The number is palindrom");
        }
        else{
            Console.WriteLine("The number isn't palindrom");
        }
    }
}

I know that I shouldn’t use int number = 122; but this was my way to understand if the code is working.

>Solution :

You should save your original number. In your case number is always 0 when comparing to the reverse number.

using System;
public class HelloWorld {
    public static void Main() {
        int number = 1222111;
        int tmp_number = number;
        int reverse = 0;
        while(tmp_number!=0){
            reverse = (reverse*10) + tmp_number%10;
            tmp_number/=10;
        }
        Console.Write(reverse);
        if(number == reverse){
            Console.WriteLine(" The number is palindrom");
        }
        else{
            Console.WriteLine(" The number isn't palindrom");
        }
    }
}

Leave a Reply