解题思路
这是一个水仙花数判断问题。水仙花数是指一个三位数,其各位数字的立方和等于该数本身。
关键点:
- 判断三位数的各位数字
- 计算立方和
- 处理多组输入
- 格式化输出结果
算法步骤:
- 预处理所有的水仙花数(只需处理一次)
- 读取每组输入范围
- 查找范围内的水仙花数
- 按格式输出结果
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
vector<int> narcissisticNumbers;
void preCalculate() {
// 预处理所有的水仙花数
for (int i = 100; i <= 999; i++) {
int a = i / 100; // 百位
int b = (i / 10) % 10; // 十位
int c = i % 10; // 个位
if (a*a*a + b*b*b + c*c*c == i) {
narcissisticNumbers.push_back(i);
}
}
}
public:
Solution() {
preCalculate();
}
void findInRange(int m, int n) {
bool found = false;
bool first = true;
for (int num : narcissisticNumbers) {
if (num >= m && num <= n) {
if (!first) cout << " ";
cout << num;
found = true;
first = false;
}
}
if (!found) cout << "no";
cout << endl;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
Solution solution;
int m, n;
while (cin >> m >> n) {
solution.findInRange(m, n);
}
return 0;
}
import java.util.*;
class Solution {
private List<Integer> narcissisticNumbers;
public Solution() {
narcissisticNumbers = new ArrayList<>();
preCalculate();
}
private void preCalculate() {
// 预处理所有的水仙花数
for (int i = 100; i <= 999; i++) {
int a = i / 100; // 百位
int b = (i / 10) % 10; // 十位
int c = i % 10; // 个位
if (a*a*a + b*b*b + c*c*c == i) {
narcissisticNumbers.add(i);
}
}
}
public void findInRange(int m, int n) {
boolean found = false;
boolean first = true;
for (int num : narcissisticNumbers) {
if (num >= m && num <= n) {
if (!first) System.out.print(" ");
System.out.print(num);
found = true;
first = false;
}
}
if (!found) System.out.print("no");
System.out.println();
}
}
public class Main {
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();
solution.findInRange(m, n);
}
sc.close();
}
}
class Solution:
def __init__(self):
self.narcissistic_numbers = []
self._pre_calculate()
def _pre_calculate(self):
# 预处理所有的水仙花数
for i in range(100, 1000):
a = i // 100 # 百位
b = (i // 10) % 10 # 十位
c = i % 10 # 个位
if a**3 + b**3 + c**3 == i:
self.narcissistic_numbers.append(i)
def find_in_range(self, m: int, n: int) -> None:
result = []
for num in self.narcissistic_numbers:
if m <= num <= n:
result.append(num)
if not result:
print("no")
else:
print(" ".join(map(str, result)))
def main():
solution = Solution()
while True:
try:
m, n = map(int, input().split())
solution.find_in_range(m, n)
except EOFError:
break
if __name__ == "__main__":
main()
算法及复杂度
- 算法:预处理 + 查找
- 时间复杂度:预处理 (常数范围),查找
- 空间复杂度:,只需存储有限的水仙花数