版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a549654065/article/details/79294238
回文数:
问题描述
1221是一个非常特殊的数,它从左边读和从右边读是一样的,编程求所有这样的四位十进制数。
输出格式
按从小到大的顺序输出满足条件的四位十进制数。
数组法:
由数组索引来判断一个数是否是回文数
下面是代码实现:
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
int[] arr = new int[4];
Arrays.fill(arr, 0);
arr[0] = 1;
for (; arr[0] != 10;) {
if (arr[0] == arr[3] && arr[1] == arr[2])
System.out.println("" + arr[0] + arr[1] + arr[2] + arr[3]);
arr[3]++;
if (arr[3] == 10) {
arr[2]++;
arr[3] = 0;
}
if (arr[2] == 10) {
arr[2] = 0;
arr[1]++;
}
if (arr[1] == 10) {
arr[1] = 0;
arr[0]++;
}
}
}
}
循环法:将一个数字倒置过来判断是否等于原来的数字
比如数字1234:
1234 = 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1;
而我们可以反过来计算看
4 * 1000 + 3 * 100 + 2 * 10 + 1 * 1 = 4321;
显而易见,1234 != 4321, 所以1234这个数字并不是回文数
下面是代码实现:
public class Main {
public static boolean isPalindrome(long d){
long k = 0;
long n = d;
while (n != 0){
k = k * 10 + n % 10;
n /= 10;
}
if (k == d)
return true;
else
return false;
}
public static void main(String args[]) {
for (int i = 1000; i < 9999; i++){
if (isPalindrome(i))
System.out.println(i);
}
}
}