LeetCode in Kotlin

2166. Design Bitset

Medium

A Bitset is a data structure that compactly stores bits.

Implement the Bitset class:

Example 1:

Input

[“Bitset”, “fix”, “fix”, “flip”, “all”, “unfix”, “flip”, “one”, “unfix”, “count”, “toString”]

[[5], [3], [1], [], [], [0], [], [], [0], [], []]

Output: [null, null, null, null, false, null, null, true, null, 2, “01010”]

Explanation:

Bitset bs = new Bitset(5); // bitset = "00000".
bs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010".
bs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010".
bs.flip(); // the value of each bit is flipped, so bitset = "10101".
bs.all(); // return False, as not all values of the bitset are 1.
bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101".
bs.flip(); // the value of each bit is flipped, so bitset = "11010".
bs.one(); // return True, as there is at least 1 index with value 1.
bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010".
bs.count(); // return 2, as there are 2 bits with value 1.
bs.toString(); // return "01010", which is the composition of bitset. 

Constraints:

Solution

class Bitset(private val sz: Int) {
    private var bits: BooleanArray
    private var flipped: BooleanArray
    private var cnt = 0

    init {
        bits = BooleanArray(sz)
        flipped = BooleanArray(sz)
        flipped.fill(true)
    }

    fun fix(idx: Int) {
        if (!bits[idx]) {
            bits[idx] = bits[idx] xor true
            flipped[idx] = flipped[idx] xor true
            cnt += 1
        }
    }

    fun unfix(idx: Int) {
        if (bits[idx]) {
            bits[idx] = bits[idx] xor true
            flipped[idx] = flipped[idx] xor true
            cnt -= 1
        }
    }

    fun flip() {
        val tmp = bits
        bits = flipped
        flipped = tmp
        cnt = sz - cnt
    }

    fun all(): Boolean {
        return cnt == sz
    }

    fun one(): Boolean {
        return cnt > 0
    }

    fun count(): Int {
        return cnt
    }

    override fun toString(): String {
        val sb = StringBuilder()
        for (b in bits) {
            sb.append(if (b) '1' else '0')
        }
        return sb.toString()
    }
}
/*
 * Your Bitset object will be instantiated and called as such:
 * var obj = Bitset(size)
 * obj.fix(idx)
 * obj.unfix(idx)
 * obj.flip()
 * var param_4 = obj.all()
 * var param_5 = obj.one()
 * var param_6 = obj.count()
 * var param_7 = obj.toString()
 */