Unicorns / VO 面试真题解析:整数转二进制字符串与嵌套列表反向深度求和

21次阅读
没有评论

Given a non-negative integer, produce a string representation of it in binary.

For example:

  • 4 => "100"
  • 15 => "1111"
  • 38 => "100110"

Given a nested list of integers, return the sum of all integers in the list weighted by their reversed level.

For example, given the list {{1,1},2,{1,1}}, the deepest level is 2. Thus the function should return 8 (four 1s with weight 1, one 2 with weight 2).

Given the list {1,{4,{6,2}}}, the function should return 19 (1 with weight 3, 4 with weight 2, 6 with weight 1, 2 with weight 1).

It is the "reverse depth" of the item in the list. For the above item:

1 (reverse-depth 3) = 1 * 3 = 3
{4} (reverse-depth 2) = 4 * 2 = 8
{6,2} (reverse-depth 1) = 6 * 1 + 2 * 1 = 8
Total = 3 + 8 + 8 = 19

这题其实包含两道经典面试题:第一题是把非负整数转换成二进制字符串,核心是不断取低位并拼接,或者使用位运算直接构造结果;第二题是嵌套列表的反向深度加权求和,重点在于先确定最大深度,再用 DFS/BFS 遍历每个整数,根据“最大深度 – 当前深度 + 1”作为权重累加。面试中常考的是对递归结构的处理、遍历过程中如何正确计算层级,以及如何利用栈或队列避免混淆普通层深度和反向深度。

正文完
 0