Given an array of ones and zeroes, convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which
is the binary representation of 1.
Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11
However, the arrays can have varying lengths, not just limited to
4.
using Test
"""
二进制各位数字向量转换为10进制数字
"""#> "二进制各位数字向量转换为10进制数字\n"
function binaryarraytonumber(arr::Vector{Int64})::Int64
# 解法一:二元函数 (i, x) 的向量化操作
# [x * 2^(i - 1) for (i, x) ∈ enumerate(reverse(arr))] |> sum
# 解法二:解析二进制字符串为10进制整数
parse(Int, join(arr), base=2)
end#> binaryarraytonumber (generic function with 1 method)
@test binaryarraytonumber([0, 1, 1, 0]) == 6#> Test Passed
#> Expression: binaryarraytonumber([0, 1, 1, 0]) == 6
#> Evaluated: 6 == 6
library(tidyverse)
binary2number <- function(arr) {
# 向量化操作 map2_dbl( .x = rev(arr), .y = 0:(length(arr) - 1), .f =
# function(x, i) x * 2^i ) %>% sum()
# 转换 k 进制字符串为 10 进制整数
str_c(arr, collapse = "") %>%
strtoi(base = 2L)
}
library(testthat)
test_that("Sample Tests", {
expect_equal(binary2number(c(0, 1, 1, 0)), 6)
})#> Test passed 🥳
const sum = require("../src/JavaScript/toolkit/Statistics").sum;
const binaryArrayToNumber = arr => {
// 向量化操作
// return sum(arr.reverse().map((x, i) => x * Math.pow(2, i)));
// 解析2进制字符串为10进制整数
return parseInt(arr.join(''), 2);
};
console.log(binaryArrayToNumber([0, 1, 1, 0]) == 6);#> true