Skip to content

Latest commit

 

History

History
executable file
·
24 lines (15 loc) · 1.99 KB

f79b.md

File metadata and controls

executable file
·
24 lines (15 loc) · 1.99 KB

Back to questions

Solution to f79b: Perfect palindromic cubes

See code at solutions/code/tutorialquestions/questionf79b

The solution involves a method:

static boolean isPalindrome(String number);

which determines whether the String parameter number (named so as in this question it is intended to store the String representation of a number) is a palindrome. The method is recursive. As a base case, strings of length 0 and 1 are (trivially) palindromes; we use the method length() of String to determine this. For a string of greater length, we check whether its first and last characters are the same. This is achieved using the charAt(int index) method, which returns the character at position index of the string.

Armed with isPalindrome, we enumerate the first 2000 cubes using a for loop. For each cube, we turn it into a string using String.valueOf, and test the resulting string using isPalindrome.

An alternative approach to isPalindrome is to take the number as an int and use arithmetic operations (based on the / and % operators) to determine whehter successive pairs of digits are equal, working from the outside in. However, such a solution is less readable than the simple String-based solution given here, and it is best to favour readability over efficienty when programming, unless there is an urgent need for efficiency.

Regarding the problem of running the program for larger numbers: integers in Java are 32-bit, and the largest positive integer representable in Java is 231-1 = 2147483647. The largest integer that, when cubed, is less than or equal to this limit, is 1290: 12903 = 2146689000. Although mathematically, 12913 = 2151685171, when computed in a Java program one gets the answer -2143282125, which is 2151685171 - 232. This is because the result wraps around.

Representing integers using the java.math.BigInteger class would avoid this problem - try it out!