在原始的InterviewStreet Codesprint上,有一個關於計算a和b之間數字的二進制補碼錶示中包含的數目的問題。我能夠通過迭代的所有測試用例的準確性,但我只能在正確的時間內傳遞兩個測試用例。有一點提到發現了一個遞歸關係,所以我切換到了遞歸,但最終花費了相同的時間。那麼任何人都可以找到比我提供的代碼更快的方法來做到這一點?輸入文件的第一個數字是文件中的測試用例。我在代碼之後提供了一個示例輸入文件。CodeSprint 2的補碼挑戰運行得太慢
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
你試過[這個招數?](http://en.wikipedia.org/wiki/Hamming_weight) – 2012-03-12 00:46:01