第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用Go實現(xiàn)BitSet?

如何用Go實現(xiàn)BitSet?

Go
瀟瀟雨雨 2021-04-09 14:11:29
我沒有在Go中找到BitSet包,所以我嘗試實現(xiàn)它。我想使用uint64數(shù)組存儲位。我需要分配uint64數(shù)組的位數(shù)。使用Java,我可以定義一個接受整數(shù)的構(gòu)造函數(shù)。雖然Go不提供構(gòu)造函數(shù),但是當(dāng)用戶調(diào)用new()時如何正確初始化BitSet'對象'呢?
查看完整描述

3 回答

?
阿波羅的戰(zhàn)車

TA貢獻1862條經(jīng)驗 獲得超6個贊

如果使用[] uint64切片存儲數(shù)據(jù),則零切片可以用作空的BitSet。實際上,附加到nil切片會為您分配一個新數(shù)組,盡管Language Specification似乎并不能保證這一點。通過這種設(shè)置,new(BitSet)將立即可用。例子:


bitset.go:


package bitset


const size = 64


type bits uint64


// BitSet is a set of bits that can be set, cleared and queried.

type BitSet []bits


// Set ensures that the given bit is set in the BitSet.

func (s *BitSet) Set(i uint) {

    if len(*s) < int(i/size+1) {

        r := make([]bits, i/size+1)

        copy(r, *s)

        *s = r

    }

    (*s)[i/size] |= 1 << (i % size)

}


// Clear ensures that the given bit is cleared (not set) in the BitSet.

func (s *BitSet) Clear(i uint) {

    if len(*s) >= int(i/size+1) {

        (*s)[i/size] &^= 1 << (i % size)

    }

}


// IsSet returns true if the given bit is set, false if it is cleared.

func (s *BitSet) IsSet(i uint) bool {

    return (*s)[i/size]&(1<<(i%size)) != 0

}

bitset_test.go:


package bitset


import "fmt"


func ExampleBitSet() {

    s := new(BitSet)

    s.Set(13)

    s.Set(45)

    s.Clear(13)

    fmt.Printf("s.IsSet(13) = %t; s.IsSet(45) = %t; s.IsSet(30) = %t\n",

               s.IsSet(13), s.IsSet(45), s.IsSet(30))

    // Output: s.IsSet(13) = false; s.IsSet(45) = true; s.IsSet(30) = false

}


查看完整回答
反對 回復(fù) 2021-04-26
  • 3 回答
  • 0 關(guān)注
  • 385 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號