Java Reference
In-Depth Information
because these have a character at the front that loses its meaning if placed at the end, and
hence are not strictly palindromic. Further, palindromic forms of certain numbers are too
long to fit in Java's 64-bit
long
integer. These cause underflow, which is trapped. As a result,
code.
Example 5-11. Palindrome.java
public
public class
class
Palindrome
Palindrome
{
public
public static
static
boolean
boolean
verbose
=
true
true
;
public
public static
static
void
void
main
(
String
[]
argv
) {
for
for
(
int
int
i
=
0
;
i
<
argv
.
length
;
i
++)
try
try
{
long
long
l
=
Long
.
parseLong
(
argv
[
i
]);
iif
(
l
<
0
) {
System
.
err
.
println
(
argv
[
i
] +
" -> TOO SMALL"
);
continue
continue
;
}
System
.
out
.
println
(
argv
[
i
] +
"->"
+
findPalindrome
(
l
));
}
catch
catch
(
NumberFormatException e
) {
System
.
err
.
println
(
argv
[
i
] +
"-> INVALID"
);
}
catch
catch
(
IllegalStateException e
) {
System
.
err
.
println
(
argv
[
i
] +
"-> "
+
e
);
}
}
/** find a palindromic number given a starting point, by
* calling ourself until we get a number that is palindromic.
*/
static
static
long
long
findPalindrome
(
long
long
num
) {
iif
(
num
<
0
)
throw
new
IllegalStateException
(
"negative"
);
iif
(
isPalindrome
(
num
))
return
throw new
return
num
;
iif
(
verbose
)
System
.
out
.
println
(
"Trying "
+
num
);
return
return
findPalindrome
(
num
+
reverseNumber
(
num
));
}
/** The number of digits in Long.MAX_VALUE */
protected
protected static
static final
final
int
int
MAX_DIGITS
=
19
;
// digits array is shared by isPalindrome and reverseNumber,