本题是位运算拼装:把若干定宽无符号整数按给定位宽依次接到同一个比特流中,再按字节对齐后转大写十六进制。
维护累加器 acc 与已写入位数 total。对每个字段 (w,v) 执行:
给定两个等长数组 sectionWidth 与 sectionValues。将每个 sectionValues[i] 写成恰好 sectionWidth[i] 位的二进制(不足则在高位补 0),再按 i=0,1,… 的顺序首尾相接。若总位数不是 8 的倍数,则在整段比特串末尾补 0,直到长度为 8 的倍数。用例保证补齐后总位数不超过 48。把结果按字节写成大写十六进制字符串返回(每字节两位,字母取 A-F)。
请实现:
packFields(sectionWidth: int[], sectionValues: int[]) -> string
两行:
sectionWidth(形如 [7, 3, 4]),1≤n≤10,1≤sectionWidth[i]≤31,n=sectionWidth.lengthsectionValues(形如 [29, 2, 15]),满足 0≤sectionValues[i]<2sectionWidth[i]一行带双引号的十六进制字符串,例如 "3ABC"。
输入:
[5, 3, 6]
[10, 5, 40]
输出:
"55A0"
说明:
10→01010,5→101,40→101000,拼接 01010101101000,右侧补 00 得 0101010110100000,即 55A0。
输入:
[8]
[255]
输出:
"FF"
说明:
恰 8 位 11111111,无需补齐。
输入:
[31]
[0]
输出:
"00000000"
说明:
31 位全 0,右侧补 1 位后共 32 位,四个字节均为 00。
Scan the QR code below with WeChat to sign in
First-time scan will create your account automatically
请使用微信扫描下方二维码完成注册