R数据帧1:
Index | Powervalue | 0 | 1 | 1
---|---|
2 | |
4 | |
3 | 8 |
16 | |
32 |
这是一个使用intToBits
转换为二进制库和tidyverse库的解决方案,用于后续的数据操作。
x <- c(20L, 50L)
map_dfr(x, ~{
bin <- intToBits(.x)
n <- 2^(seq_len(32) - 1)
possible <- paste(n[as.logical(bin)], collapse = ", ")
data.frame(combinevalue = .x,
possiblecodes = possible,
y = rev(as.integer(bin)),
n = rev(paste0("code_", n)))
}) |>
pivot_wider(names_from = n, values_from = y)
##> # A tibble: 2 × 34
##> combinevalue possiblecodes code_2147483648 code_1073741824 code_536870912
##> <int> <chr> <int> <int> <int>
##> 1 20 4, 16 0 0 0
##> 2 50 2, 16, 32 0 0 0
##> # … with 29 more variables: code_268435456 <int>, code_134217728 <int>,
##> # code_67108864 <int>, code_33554432 <int>, code_16777216 <int>,
##> # code_8388608 <int>, code_4194304 <int>, code_2097152 <int>,
##> # code_1048576 <int>, code_524288 <int>, code_262144 <int>,
##> # code_131072 <int>, code_65536 <int>, code_32768 <int>, code_16384 <int>,
##> # code_8192 <int>, code_4096 <int>, code_2048 <int>, code_1024 <int>,
##> # code_512 <int>, code_256 <int>, code_128 <int>, code_64 <int>, …
尝试下面的递归
f <- function(n) {
if (n == 0) {
return(NULL)
}
v <- 2^floor(log2(n))
c(Recall(n - v), v)
}
得到
> f(50)
[1] 2 16 32
> f(20)
[1] 4 16