解题思路
这是一个数字特性判断问题。需要在给定范围内找出所有的水仙花数,即各位数字的立方和等于数字本身的三位数。
关键点:
- 判断一个数是否为水仙花数
- 处理多组测试数据
- 按照格式要求输出结果
- 处理没有水仙花数的情况
算法步骤:
- 读取每组测试数据的范围m和n
- 在范围内遍历每个数字
- 判断是否为水仙花数
- 按要求格式化输出结果
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isNarcissistic(int num) {
int sum = 0;
int temp = num;
// 计算各位数字的立方和
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == num;
}
vector<int> solve(int m, int n) {
vector<int> result;
// 在范围内查找水仙花数
for (int i = m; i <= n; i++) {
if (isNarcissistic(i)) {
result.push_back(i);
}
}
return result;
}
};
int main() {
int m, n;
Solution solution;
while (cin >> m >> n) {
vector<int> result = solution.solve(m, n);
if (result.empty()) {
cout << "no" << endl;
} else {
for (int i = 0; i < result.size(); i++) {
if (i > 0) cout << " ";
cout << result[i];
}
cout << endl;
}
}
return 0;
}
import java.util.*;
public class Main {
static class Solution {
private boolean isNarcissistic(int num) {
int sum = 0;
int temp = num;
// 计算各位数字的立方和
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == num;
}
public List<Integer> solve(int m, int n) {
List<Integer> result = new ArrayList<>();
// 在范围内查找水仙花数
for (int i = m; i <= n; i++) {
if (isNarcissistic(i)) {
result.add(i);
}
}
return result;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Solution solution = new Solution();
while (sc.hasNext()) {
int m = sc.nextInt();
int n = sc.nextInt();
List<Integer> result = solution.solve(m, n);
if (result.isEmpty()) {
System.out.println("no");
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.size(); i++) {
if (i > 0) sb.append(" ");
sb.append(result.get(i));
}
System.out.println(sb.toString());
}
}
sc.close();
}
}
class Solution:
def is_narcissistic(self, num: int) -> bool:
# 计算各位数字的立方和
sum_cubes = sum(int(d) ** 3 for d in str(num))
return sum_cubes == num
def solve(self, m: int, n: int) -> list:
# 在范围内查找水仙花数
return [i for i in range(m, n + 1) if self.is_narcissistic(i)]
# 读取输入并处理
solution = Solution()
while True:
try:
m, n = map(int, input().split())
result = solution.solve(m, n)
if not result:
print("no")
else:
print(" ".join(map(str, result)))
except EOFError:
break
算法及复杂度
- 算法:枚举
- 时间复杂度:,其中 和 是给定的范围
- 空间复杂度:,其中 是找到的水仙花数的数量