c++分别使用枚举器、迭代器实现输出N以内所有的水仙花数
时间: 2024-04-25 08:05:21 浏览: 83
枚举器实现:
```java
import java.util.Enumeration;
import java.util.Vector;
public class NarcissisticNumber {
public static void main(String[] args) {
int n = 1000; // 输出N以内的水仙花数
Vector<Integer> v = new Vector<>();
for (int i = 100; i <= n; i++) {
int sum = 0;
int temp = i;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == i) {
v.add(i);
}
}
Enumeration<Integer> en = v.elements();
while (en.hasMoreElements()) {
System.out.print(en.nextElement() + " ");
}
}
}
```
迭代器实现:
```java
import java.util.ArrayList;
import java.util.Iterator;
public class NarcissisticNumber {
public static void main(String[] args) {
int n = 1000; // 输出N以内的水仙花数
ArrayList<Integer> list = new ArrayList<>();
for (int i = 100; i <= n; i++) {
int sum = 0;
int temp = i;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == i) {
list.add(i);
}
}
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
}
}
```
阅读全文