我刚刚对鳕鱼进行了编码采访
我被要求实施以下内容,但我无法在20分钟内完成,现在我在这里从这个社区获得想法
编写一个函数public int whole_cubes_count ( int A,int B ),它应返回范围内的整个立方体
例如,如果A = 8且B = 65,则范围内的所有可能的立方体都是2 ^ 3 = 8,3 ^ 3 = 27和4 ^ 3 = 64,因此该函数应返回计数3
我无法弄清楚如何将数字识别为整个立方体.我该如何解决这个问题?
A和B的范围可以从[-20000到20000]
这是我试过的
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Run Code Online (Sandbox Code Playgroud)
对于积极的立方体:
i = 1
while i^3 < max
++i
Run Code Online (Sandbox Code Playgroud)
类似地对于负立方体但在比较中具有绝对值.
为了使这个更一般的,你需要找到的值i,其中i^3 >= min,在这两个案件min和max为正.如果两者都是否定的min,max则类似的解决方
沮丧和肮脏,这就是我说的.
如果你只有20分钟,那么他们不应该期待超级优化的代码.所以不要尝试.发挥系统的限制,只说+20,000到-20,000作为范围.你知道立方体值必须在27以内,因为27*27*27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4354 次 |
| 最近记录: |