题目描述
一个整数如果由相同的数字构成,则称为完美整数。例如:
1、11、333是完美整数。12、19、101是不完美整数。
现在,你需要计算给定区间 [x, y] 中有多少个整数是完美整数。
测试样例
样例1
输入:x = 1 ,y = 10
输出:9
样例2
输入:x = 2 ,y = 22
输出:10
思路
- 遍历区间:从 x 到 y 遍历所有的整数。
- 判断完美整数。
- 计数:如果一个整数是完美整数,则计数器加一。
Java代码
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) {
// Add your test cases here
System.out.println(solution(1, 10) == 9);
System.out.println(solution(2, 22) == 10);
}
}
复杂度分析
时间复杂度:O(n * m),其中 n 是区间的长度,m 是整数的位数(在最坏的情况下,判断一个整数是否是完美整数需要遍历其所有位数)。
空间复杂度:O(1),只使用了常量级别的额外空间。