本系列整理了10个工作量和难度适中的Golang小项目,适合已经掌握Go语法的工程师进一步熟练语法和常用库的用法。
问题描述:
有一组非负整数,实现一个位向量类型,能在O(1)时间内完成插入、删除和查找等操作。
要点:
- 实现Has(uint)、Add(uint)、Remove(uint)、Clear()、Copy()、String()、AddAll(…uint)、UnionWith()、IntersectWith()、DifferenceWith()、SymmetricDifference()方法。
拓展:
- 使用uint存储而不是uint32或uint64这样限定字长的类型。
代码实现:
import (
"bytes"
"fmt"
)
func (s *IntSet)countBit(n uint)int{
count := 0
for n != 0{
n = n & ( n - 1 )
count += 1
}
return count
}
func (s *IntSet)calWordBit(x int)(word int, bit uint) {
word, bit = x / wordSize, uint(x%wordSize)
return
}
const wordSize = 32 << (^uint(0) >> 63)
// An IntSet is a set of small non-negative integers.
// Its zero value represents the empty set.
type