Java Reference
In-Depth Information
which is. The number 17,892, which my son Benjamin picked out of the air, requires 12
rounds to generate a palindrome, but it does terminate:
C:\javasrc\numbers> java numbers.Palindrome 72 142 1951 17892
Trying 72
72->99
Trying 142
142->383
Trying 1951
Trying 3542
1951->5995
Trying 17892
Trying 47763
Trying 84537
Trying 158085
Trying 738936
Trying 1378773
Trying 5157504
Trying 9215019
Trying 18320148
Trying 102422529
Trying 1027646730
Trying 1404113931
17892->2797227972
C:\javasrc\numbers>
If this sounds to you like a natural candidate for recursion, you are correct. Recursion in-
volves dividing a problem into simple and identical steps, which can be implemented by a
function that calls itself and provides a way of termination. Our basic approach, as shown in
method findPalindrome , is:
long findPalindrome(long num) {
if (isPalindrome(num))
return num;
return findPalindrome(num + reverseNumber(num));
}
That is, if the starting number is already a palindromic number, return it; otherwise, add it to
its reverse, and try again. The version of the code shown here handles simple cases directly
(single digits are always palindromic, for example). We won't think about negative numbers
Search WWH ::




Custom Search