Computer Science Canada Help with palindrome |
Author: | Vyth_of_Darkness [ Fri Jun 08, 2007 9:10 am ] |
Post subject: | Help with palindrome |
trying to use ready to program to make a program on java so that reads a five digit number and determines whether or not it a palindrome. I have been trying to figuring it out but i need major help becuase i just started using java and need to finish it in a day or two. |
Author: | rollerdude [ Fri Jun 08, 2007 12:11 pm ] |
Post subject: | Re: Help with palindrome |
i dont really know java, but you need to see if the first number is the same as the last, and second with the fourth, if thet are, then its a palindrome... i could give you the turing equivilent if how to do that, but not in java var num:int(5) var pal:boolean:=false get num if intstr(num)(1)=intstr(num)(5) and intstr(num)(2)=intstr(num)(4) then put "It is a palindrome" end if in turing, strings are stored as a one-dimensial array, i dont know if java has an intstr function, which turns the number into a string, but i hope it at least helps a little |
Author: | inflamous [ Fri Jun 08, 2007 3:31 pm ] |
Post subject: | Re: Help with palindrome |
if the number is a string and always 5 digits, you can probably just hard code it if (number.charAt (0) == number.charAt (4) && number.charAt (1) == number.charAt (3)) { System.out.println ("Is a Palindrome") } else { System.out.println ("Not a Palindrome") } |
Author: | richcash [ Fri Jun 08, 2007 5:41 pm ] | ||
Post subject: | Re: Help with palindrome | ||
You do not need to use strings. How do you find out if a number, x, is a palindrome? 1. Find the number of digits in x. Take the log (base 10) of x. Round the result down and add 1. 2. Use a for loop to look at the first half of the digits. You know the length, so make your for loop go up to length / 2 (rounded down because we don't care about the middle digit). 3. Check if each digit from the right matches each digit from the left. As soon as a pair of digits that should match don't, return false. To get the ith digit in x, divide x by 10^i, round down, and modulus 10. The ith digit should match the (length-1-i)th digit. Right? If length is 5 then 0th should match 4th, 1st should match 3rd, etc. 4. You do not need to check the middle digit, so once the for loop is done (without false being returned) return true. So return false when the digits that should match don't. If all of them match, then return true.
|