1.题意
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.
题目的意思是给定一个整型数组,数组的每个元素只能取0或1,将数组所有元素按序组成的二进制串转换成十进制的数值
2. 代码
代码很简单,按照二进制计算的思路来写就行,假设返回的值是sum,初始化为0,从第一位开始,进行sum = sum * 2,然后再加上当前值,直到算完最后一位,我这里使用位运算,事实上和前面是一样的,只是更贴合二进制计算的本质
import java.util.List;
public class BinaryArrayToNumber {
public static int ConvertBinaryArrayToInt(List<Integer> binary) {
// Your Code
int sum = 0;
for(int i = 0;i < binary.size();i++){
sum = sum << 1;
sum = sum | binary.get(i);
}
return sum;
}
}