Palindrome is not working [duplicate]
Possible Duplicate:
How do I check if a number is a palindrome?
Hello All i want to make program to check whether palindrome number or not when user input the number. But my work does not work at all... Can you guys help me...
class Program
{
static void Main(string[] args)
{
int i = 0, j = 0 ;
int numbers =Convert.ToInt32( Console.ReadLine());
i = numbers % 10;
do
{
j = numbers / 10;
}
while (j < 10);
if (i == j)
开发者_JAVA技巧 {
Console.WriteLine(" this is palindrome number");
}
else
{
Console.WriteLine("not a palindrome");
}
The quickest way is to reverse the string and compare it to the original. You don't really need the integer conversion.
You may want to filter or correct the user's input by stripping leading zeroes (i.e. in 010
). For example : string number = Convert.ToInt32(Console.ReadLine()).ToString();
You don't have to convert it to integer. You can check it from the string.
Take the first character and the last character compare those .
Iterate the first pointer +1 and the last pointer -1 then compare.
Continue this process upto you are in middle of the string.
First of all by converting the digits to an Int32
, the number of digits a user can enter are limited.
By using the modulo operation, the i
variable will contain the last digit of the entered number.
By dividing the number by 10, j
should eventually contain the first digit entered. However you aren't dividing it "until j
is smaller than 10", but you're dividing it "while j
is smaller than 10", effectively making the contents of j
depend on the number of digits entered.
Even if you would fix the while
condition, this code will only check the first and last digit, making it function only for 1, 2 and 3 digit numbers.
You'll need something like this:
bool isPalindrome = true;
string s = "300212003";
for (int i = 0; i < (s.Length / 2); i++)
{
if (s[i] != s[s.Length - i - 1])
{
isPalindrome = false;
break;
}
}
Console.WriteLine(isPalindrome);
It's faster than reverting a string and comparing it, only need O(n/2) operations.
a disscussion
palindrome check
C# code to check palindrome
You can follow these links .
#include<stdio.h>
#include<math.h>
void main()
{
long int n, num, rev = 0, dig;
clrscr();
printf("\n\n\t ENTER A NUMBER...: ");
scanf("%ld", &num);
n = num;
while(num>0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
if (n == rev)
printf("\n\t GIVEN NUMBER IS A PALINDROME");
else
printf("\n\t GIVEN NUMBER NOT A PALINDROME");
getch();
}
Something is palindrome when you can read it either way, so when the reverse is the same as the original. So just reverse your input string and compare it to the original.
精彩评论