Monday, May 24, 2010

How can i write a c language program to determine whether 4 digits are palindrome or no?

please help just by telling me how can i define palindrome in C program, i don't want the whole program.

How can i write a c language program to determine whether 4 digits are palindrome or no?
If you are only worried about 4 digits then:





If variable s is the 4 digit string


If (s[0] is equal to s[3]) and (s[1] is equal to s[2]) then it is a 4 digit palindrome.





Use your knowledge of C to implement this suedo code.





==Edit==


* Sheqi actually has an elegant solution (I gave it a thumbs up) but reversing the 4 digit is an extra step you don't need.


* richarduie has an example of what I said.


* I'm not sure what Alexanders code does without tracing it. It might work if when you said "digits" you meant numbers but I would trace it before I handed that one in.


* Curious George has some C++ code so don't copy that verbatim to answer your "C" question. It will just raise eyebrows.
Reply:This will work for any number of type "int":





int a = /*needed number*/;





int x = 0;


int z = a;


while (z)


{


x *= 10;


x += z%10;


z /= 10;


}


if (x==a)


{


/*number is a palindrome*/


}


else


{


/*number isn't a palindrome*/


}
Reply:bool isPalindrome(const std::string %26amp;str)


{


std::string::const_reverse_iterator itEnd = str.rbegin()++;


for (std::string::const_iterator itStart = str.begin(); itStart %26lt; itEnd.base(); ++itStart, ++itEnd)


{


if (*itStart != *itEnd)


{


return false;


}


} return true;


}
Reply:For a four-digit number, break the number into digits. For instance, 5678 would decompose into 5, 6, 7, 8. Compare the first and last for equality. Compare the second and third for equality. If both pairs are equal, the number is palindromic.





E.g.,





2452 --%26gt; (2 == 2) %26amp;%26amp; (4 == 5) --%26gt; true %26amp;%26amp; false --%26gt; false





3663 --%26gt; (3 == 3) %26amp;%26amp; (6 == 6) --%26gt; true %26amp;%26amp; true --%26gt; true





2452 is not a palindormic number; 3663 is.
Reply:A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction.





Reverse the order of the string and compare with the original.


No comments:

Post a Comment