纯纯 bitMap Buddy System

定义buddy system为一棵complete binary tree。一个node可能为0也可能为1
. 它的value为1,当且仅当它所有的child的value均为1.
1
/
1 2
/ \ /
1 2 3 4
/ / \ / \ /
1 2 3 4 5 6 7 8

实现下列的method。
1' clearBit(int offset, int len);
2' setBit(int offset, int len);

public class BuddySystem {
    int N;
    int[][] nums;
    public BuddySystem(int n) {
        this.N = n;
        nums = new int[n][0];
        for (int i = 0; i < n; i++) {
            nums[i] = new int[1 << i];
        }
    }
    public void clearBit(int offset, int len) {
        while(offset >= 0) {
            nums[offset--][len] = 0;
            len /= 2;
        }
    }
    public void setBit(int offset, int len) {
        while (offset >= 0) {
            nums[offset][len] = 1;
            if (len % 2 == 0) {
                if (nums[offset][len + 1] == 0) break;
            } else if (nums[offset][len - 1] == 0) break;
            offset--;
            len /= 2;
        }
    }
    public void print(){
        for (int[] row : nums) {
            System.out.println(Arrays.toString(row));
        }
    }
    public static void main(String[] args) {
        BuddySystem bs = new BuddySystem(4);
        bs.print();
        bs.setBit(3, 6);
        bs.print();
        bs.setBit(3,7);
        bs.print();
        bs.clearBit(3,6);
        bs.print();
    }
}

你可能感兴趣的:(纯纯 bitMap Buddy System)