You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
28 lines
667 B
28 lines
667 B
package cap3
|
|
|
|
// Ex9t1 整数拆解为2的幂之和(返回整数的二进制bit取值情况,bit的idx对应相应的幂)
|
|
func Ex9t1(num int) []bool {
|
|
// 传进来的是int,一般是32bit,这里就用64来存bit,肯定够了
|
|
bits := make([]bool, 0, 64)
|
|
for i := 0; num != 0; i++ {
|
|
bits = append(bits, num%2 == 1)
|
|
num /= 2
|
|
}
|
|
|
|
return bits
|
|
}
|
|
|
|
// Ex9t2 整数拆解为2的幂之和(返回幂取值)
|
|
func Ex9t2(num int) []uint8 {
|
|
// 传进来的是int,一般是32bit,这里就用64来存bit,肯定够了
|
|
bits := make([]uint8, 0, 64)
|
|
for i := uint8(0); num != 0; i++ {
|
|
if num%2 == 1 {
|
|
bits = append(bits, i)
|
|
}
|
|
|
|
num /= 2
|
|
}
|
|
|
|
return bits
|
|
}
|
|
|