【发布时间】:2021-09-01 17:01:15
【问题描述】:
我对此有点陌生,刚刚学习了循环。所以我想输入 187654321, 998765432 但我认为我写的这个东西效率太低以至于它只是超时:/它适用于较小的数字!将不胜感激任何帮助/提示呵呵:')
import java.util.*;
class PowerOf3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter start and end: ");
int start = sc.nextInt();
int end = sc.nextInt();
int ans = countNumbers(start, end);
System.out.println("Answer = "+ans);
}
// Count the number of integers from start to
// end (both inclusive) that are power of 3
public static int countNumbers(int start, int end) {
int count = 0;
if (start == 1) {
count = -1;
} else {
count =0;
}
while (end>=start) {
double n = end;
while (n>1) {
n = (double) n/3;
}
if (n==1) {
count++;
}
end--;
}
return count; // stub, to be replaced by your code
}
}
【问题讨论】:
-
你能举个小数字的例子吗?这将帮助其他人了解您的代码将做什么?可能会提供更好的解决方案。
-
如果inner-while循环对应库中的数学函数,你可以尝试使用它。
-
在 1 和
Integer.MAX_VALUE之间只有 3 的 20 次幂。您可以将这些存储在一个列表中,然后只计算开始和结束之间的数字。 -
@AntiqTech 哦,是的,我刚刚看到了!我现在就试试看!谢谢你
标签: java loops while-loop