我刚刚接受了一个关于 codility 的编码面试
我被要求实现以下内容,但我无法在 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));
}
}
最佳答案
下流和肮脏,这就是我所说的。
如果您只有 20 分钟,那么他们不应该期待 super 优化的代码。所以甚至不要尝试。发挥系统的限制,说只有 +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;
}
关于java - 采访 : Find the whole cubes between range of two Integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811251/