gpt4 book ai didi

arrays - 按位移位以及此解决方案为何有效

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:37 25 4
gpt4 key购买 nike

我一直在 codefights.com 上进行代码战斗,我在下面遇到了这个问题。我已经自己解决了这个问题,但是当我研究其他人的解决方案时,我发现一个比我的短得多的解决方案,但我似乎无法理解他们为什么这样做。

问题是:

You are given an array of up to four non-negative integers, each less than 256. Your task is to pack these integers into one number M in the following way:

The first element of the array occupies the first 8 bits of M; The second element occupies next 8 bits, and so on. Return the obtained integer M.

Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example.

Example

For a = [24, 85, 0], the output should be arrayPacking(a) = 21784.

An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary. After packing these into one number we get 00000000 01010101 00011000 (spaces are placed for convenience), which equals to 21784.

他们的回答是:

func arrayPacking(a []int) (sum int) {
for i := range a {
sum += a[len(a) - i - 1] << uint((len(a) - i - 1) * 8)
}
return
}

这段代码如何仅通过使用 0、8、16 等间隔返回正确的偏移量?我最近一直在按位研究很多,但我似乎仍然无法理解为什么它有效。

最佳答案

首先,用 Go 编写解决方案。我们将 little-endian、base-256 数字转换为 base-2(二进制)数字。左移 8 位乘以 256。

package main

import (
"fmt"
)

func pack(digits []int) (number int) {
// digits are little-endian, base-256 (1 << 8 = 256)
for i, digit := range digits {
number += digit << uint(i*8)
}
return number
}

func main() {
a := []int{24, 85, 0}
m := pack(a)
fmt.Println(m)
}

Playground :https://play.golang.org/p/oo_n7CiAHwG

输出:

21784

现在你应该能猜出他们丑陋的答案了:

func arrayPacking(a []int) (sum int) {
for i := range a {
sum += a[len(a) - i - 1] << uint((len(a) - i - 1) * 8)
}
return
}

关于arrays - 按位移位以及此解决方案为何有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com