Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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");
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading