First, let's look at the definition of palindrome numbers:
Palindromic numbers: Let n be an arbitrary natural number. If the natural numbers n1 and n obtained by reversing the digits of n are equal, then n is called a palindromic number. For example, 12321 and 666 are palindrome numbers, but 1234 is not a palindrome number.
The specific implementation ideas are as follows:
- First invert the numbers to determine whether the inverted numbers are equal to the original numbers, if they are equal, they are palindrome numbers;
- Traverse to find all palindromic numbers less than a given positive integer;
The specific code to judge the palindrome number:
private static boolean isPalindrome(int number) {
if (number < 0) {
return false;
}
int tmpNumber = number;
long reversedNumber = 0;
while (tmpNumber != 0) {
reversedNumber = reversedNumber * 10 + (tmpNumber % 10);
tmpNumber = tmpNumber / 10;
}
return reversedNumber == number;
}
Print all palindromes less than the given range of positive integers:
private static void printPalindrome(int maxNumber) {
for (int num = 1; num < maxNumber; num++) {
if (isPalindrome(num)) {
System.out.println(num);
}
}
}
Print all palindrome numbers in the specified range of positive integers:
private static void printPalindrome(int minNumber, int maxNumber) {
for (int num = minNumber; num < maxNumber; num++) {
if (isPalindrome(num)) {
System.out.println(num);
}
}
}
Test verification
public static void main(String[] args) {
System.out.println("小于20的回文数字:");
printPalindrome(20);
System.out.println("1000 - 1100之间的回文数字:");
printPalindrome(1000, 1100);
}
The output is as follows:
Palindromic numbers less than 20:
1
2
3
4
5
6
7
8
9
11
Palindromic numbers between 1000 - 1100:
1001
For more knowledge points related to Java interviews, you can pay attention to the [Java Interview Manual] applet, which involves Java foundation, multithreading, JVM, Spring, Spring Boot, Spring Cloud, Mybatis, Redis, database, data structure and algorithm.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。