完美整数

43 阅读1分钟

public class Main { public static int solution(int x, int y) { // Edit your code here int temp = 0; int num = y - x + 1; for (int i = x; i <= y; i ++ ) { int temp1 = i; while (temp1 != 0) {
temp = temp1 % 10; temp1 = temp1 / 10; if (temp1 != 0 && temp != temp1 % 10) { num = num - 1; break; } } } return num; } public static void main(String[] args) { System.out.println(solution(1, 10) == 9); System.out.println(solution(2, 22) == 10); } } 算法思路分析 初始化: temp:用于临时存储当前数字的个位数。 num:初始化为y - x + 1,即给定范围内的整数总数 遍历: 使用for循环遍历范围[x, y]内的每个整数i。 检查: 对于每个整数i,将其赋值给temp1。 使用while循环,在temp1不为零的情况下,不断执行以下操作: 计算temp1的个位数,并将其存储在temp中。 将temp1除以10,以移除其个位数。 检查temp1是否不为零且temp(当前个位数)不等于temp1的新个位数(这是错误的逻辑,因为它试图通过比较相邻位来识别回文数,但这并不正确)。 更新: 如果上述条件满足(即错误的回文数检查条件),则将num减1,并跳出内部while循环。 返回结果: 返回num,即给定范围内满足(错误定义的)条件的整数数量。