元のInterviewStreet Codesprintには、aとbの間の2の補数表示の1の数を数えることに関する質問があります。私は繰り返しを使ってすべてのテストケースを正確に渡すことができましたが、正しい時間内に2つしか渡すことができませんでした。再発関係を見つけることについてのヒントがありましたので、再帰に切り替わりましたが、同じ時間がかかりました。だから誰も私が提供したコードよりこれを行うためのより速い方法を見つけることができますか?入力ファイルの最初の数は、ファイル内のテストケースです。コードの後ろにサンプル入力ファイルを用意しました。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://ja.wikipedia.org/wiki/Hamming_weight) –