【发布时间】:2012-03-28 10:18:48
【问题描述】:
在原来的InterviewStreet Codesprint 上,有一个关于计算 a 和 b 之间数字的二进制补码表示中的个数的问题。我能够使用迭代通过所有测试用例的准确性,但我只能在正确的时间内通过两个。有提示提到找到递归关系,所以我切换到递归,但最终花费了相同的时间。那么任何人都可以找到比我提供的代码更快的方法吗?输入文件的第一个数字是文件中的测试用例。我在代码之后提供了一个示例输入文件。
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numCases = scanner.nextInt();
for (int i = 0; i < numCases; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(count(a, b));
}
}
/**
* Returns the number of ones between a and b inclusive
*/
public static int count(int a, int b) {
int count = 0;
for (int i = a; i <= b; i++) {
if (i < 0)
count += (32 - countOnes((-i) - 1, 0));
else
count += countOnes(i, 0);
}
return count;
}
/**
* Returns the number of ones in a
*/
public static int countOnes(int a, int count) {
if (a == 0)
return count;
if (a % 2 == 0)
return countOnes(a / 2, count);
else
return countOnes((a - 1) / 2, count + 1);
}
}
输入:
3
-2 0
-3 4
-1 4
Output:
63
99
37
【问题讨论】:
-
你试过this trick?
标签: java performance algorithm recursion binary