나는 이렇게 학습한다/Algorithm & SQL
Ones and Zeros
daco2020
2022. 2. 12. 11:05
반응형
문제 설명
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.
Examples:
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.
해결 방법
1. arr안의 숫자들을 합쳐서 2진수 로 만들다.
2. 2진수에 대한 10진수 값을 구한다.
def binary_array_to_number(arr):
bin_str = ''.join([str(i) for i in arr])
result = int(bin_str, 2)
return result
배열안에 있는 숫자들을 str로 바꾸어 join으로 합쳐주었다.
int에서 문자열로 된 다른 숫자체계를 넣고,
두번째 인수로 해당 숫자체계의 수를 넣어주면(여기서는 2진수이므로 '2') 10진수 값으로 반환해준다.
다른 숫자체계를 10진수로 바꾸는 방법을 새롭게 알게되었다.
반응형