codechef问题的链接是:
http://www.codechef.com/problems/DCE05
问题是:
参赛选手必须排队。从1开始,他们按照他们的顺序给出数字。队长然后移除所有站在奇数位置的参赛者。
最初,站着的人有数字 - 1,2,3,4,5 ......
第一次传球后,剩下的人是 - 2,4,......
第二次传球后 - 4,....
等等。
您想以船员身份登船。鉴于某个职位的申请人总数,找到最佳位置,以便您被选中。
输入
第一行包含测试用例数t(t <= 10 ^ 5)。接下来的t行包含整数n,即该案例的申请人数。 (N&LT = 10 ^ 9)
输出
显示t行,每行包含一个整数,在TITANIC赢得一个位置的地方。
示例
输入:
2
5
12
输出:
4
8
我注意到了一种模式:
For 1 : Output=1 (2^0)
For 2 : Output=2 (2^1)
For 3 : Output=2 (2^1)
For 4 : Output=4 (2^2)
For 5 : Output=4 (2^2)
For 6 : Output=4 (2^2)
For 7 : Output=4 (2^2)
For 8 : Output=8 (2^3) ans so on
所以答案每次都是2的最近幂,即&lt; = number。
这是我的代码:
import java.io.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int x=0;
int output[]=new int[n];
for(int i = 0; i < n; i++)
{
output[i]=(int) Math.pow(2, Math.floor(Math.log(Integer.parseInt(br.readLine()))/Math.log(2)));
}
for(int i=0; i<n;i++)
{
System.out.println(output[i]);
}
}
}
方法1:我使用Math.pow()来计算循环中2的幂,直到变为&lt; = number,我认为这是非常低效的。
方法2:我用循环中的* 2替换了Math.pow()。 (仍然超过时间)
方法3:我用循环中的左移替换乘法2。 (仍然超过时间)
方法4:我用log 2逻辑替换了循环,我在stackverflow上找到了。 (仍然超过时间)
仍然显示超出时间。 最快的方法是什么?
答案 0 :(得分:2)
确保Integer.highestOneBit
是代码中最快的部分。即使您的原始版本最有可能比解析和格式化更快。
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (sb.length() > 100000) {
System.out.print(sb);
sb.delete(0, sb.length());
}
final int x = Integer.parseInt(br.readLine());
final int y = Integer.highestOneBit(x);
sb.append(y).append("\n");
}
System.out.print(sb);
计算是微不足道的,所以我猜测问题是输出并增加了一些缓冲。可能有一种更简单的方法,但我不在乎。
另一种可能性是该网站不确定地工作,我很幸运。