【问题标题】:CodeSprint 2's Complement challenge running too slowlyCodeSprint 2 的 Complement 挑战运行太慢
【发布时间】: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

【问题讨论】:

标签: java performance algorithm recursion binary


【解决方案1】:

第一步是替换

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);
}

递归到 log2 a 的深度,实现速度更快,例如著名的 bit-twiddling

public static int popCount(int n) {
    // count the set bits in each bit-pair
    // 11 -> 10, 10 -> 01, 0* -> 0*
    n -= (n >>> 1) & 0x55555555;
    // count bits in each nibble
    n = ((n >>> 2) & 0x33333333) + (n & 0x33333333);
    // count bits in each byte
    n = ((n >> 4) & 0x0F0F0F0F) + (n & 0x0F0F0F0F);
    // accumulate the counts in the highest byte and shift
    return (0x01010101 * n) >> 24;
    // Java guarantees wrap-around, so we can use int here,
    // in C, one would need to use unsigned or a 64-bit type
    // to avoid undefined behaviour
}

它使用四次移位、五次按位与、一次减法、两次加法和一次乘法,总共有 13 条非常便宜的指令。

但除非范围非常小,否则比计算每个数字的位数要好得多

让我们首先考虑非负数。从 0 到 2k-1 的数字都设置了最多 k 位。每个位都设置在其中的一半中,因此位的总数为k*2^(k-1)。现在让2^k &lt;= a &lt; 2^(k+1)。数字0 &lt;= n &lt;= a 中的总位数是数字0 &lt;= n &lt; 2^k 中的位数和数字2^k &lt;= n &lt;= a 中的位数之和。正如我们在上面看到的,第一个计数是k*2^(k-1)。在第二部分中,我们有a - 2^k + 1 数字,每个数字都有 2k 位设置,忽略前导位,这些位与数字 0 &lt;= n &lt;= (a - 2^k) 相同,所以

totalBits(a) = k*2^(k-1) + (a - 2^k + 1) + totalBits(a - 2^k)

现在是负数。在二进制补码中,-(n+1) = ~n,所以数字-a &lt;= n &lt;= -1 是数字0 &lt;= m &lt;= (a-1) 的补码,数字-a &lt;= n &lt;= -1 中设置位的总数是a*32 - totalBits(a-1)

对于a &lt;= n &lt;= b范围内的总位数,我们必须加或减,这取决于范围的两端是相反的符号还是相同的符号。

// if n >= 0, return the total of set bits for
// the numbers 0 <= k <= n
// if n < 0, return the total of set bits for
// the numbers n <= k <= -1
public static long totalBits(int n){
    if (n < 0) {
        long a = -(long)n;
        return (a*32 - totalBits((int)(a-1)));
    }
    if (n < 3) return n;
    int lg = 0, mask = n;
    // find the highest set bit in n and its position
    while(mask > 1){
        ++lg;
        mask >>= 1;
    }
    mask = 1 << lg;
    // total bit count for 0 <= k < 2^lg
    long total = 1L << lg-1;
    total *= lg;
    // add number of 2^lg bits
    total += n+1-mask;
    // add number of other bits for 2^lg <= k <= n
    total += totalBits(n-mask);
    return total;
}

// return total set bits for the numbers a <= n <= b
public static long totalBits(int a, int b) {
    if (b < a) throw new IllegalArgumentException("Invalid range");
    if (a == b) return popCount(a);
    if (b == 0) return totalBits(a);
    if (b < 0) return totalBits(a) - totalBits(b+1);
    if (a == 0) return totalBits(b);
    if (a > 0) return totalBits(b) - totalBits(a-1);
    // Now a < 0 < b
    return totalBits(a) + totalBits(b);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多