java - 如何用Java编写一个强数字函数
问题描述
在此处输入图像描述我正在尝试解决这个问题:
a) 使用以下标头编写一个方法,该方法采用整数 n 并返回 n 的值!(发音为 n 阶乘)计算如下:
public static int factorial(int n)
请注意,0!= 1 和 n! = n * (n-1) * (n-2)*.....*1。示例:factorial(4) 将返回 24,即 = 4*3*2*1。
b) 使用以下标头编写一个方法,该方法采用整数 x 并在 x 是强数字时返回 true。否则,它返回 false。
public static boolean isStrongNumber(int x)
请注意,该isStrongNumber
方法应调用阶乘方法来计算 x 中每个数字的阶乘。
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int z;
int q = 0;
int sum = 0;
while (temp > 0) {
x = x % 10;
z = factorial(x);
q += z;
if (q == temp) {
System.out.print(q + " ");
return true;
}
}
}
这是我的答案,但每次尝试运行它时都会出错。
解决方案
您没有在isStrongNumber
方法结束时返回布尔值
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
sum += factorial(num % 10);
num /= 10;
}
return sum == originalNum;
}
,main
函数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = Integer.parseInt(scanner.nextLine());
Set<Integer> set = new TreeSet<>();
for (int i = 1; i <= number; i++) {
if (isStrongNumber(i)) {
set.add(i);
}
}
System.out.println("The Strong numbers between 1 and " + number + " are:");
System.out.println(set);
scanner.close();
}
, 输出为输入100000
Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]
推荐阅读
- php - JSON POST Empty 使用 cURL 命令
- javascript - 使用正则表达式查找对象的值
- bash - 在保留行组的同时拆分文件
- coq - 如何在 Coq 中重写给定的两个依赖类型相等
- git - git 是否有一个命令可以将工作树重置为 HEAD 但保留索引的分阶段更改?
- dictionary - 将值插入地图时出现恐慌/错误
- virtual-machine - Virtualbox 没有端口转发端口 8080 但其他端口都可以
- kubernetes - 使用一个 API 请求从节点中删除特定的污点
- excel - MS Access VBA 正在创建多个报告电子邮件,并且参数未存储表单中的引用
- java - 为什么网格不尊重约束?