几点。首先,你的代码中实际存在一个错误 - 尝试传递它00000000(8个零),看看会发生什么。
至于效率,您可以节省一些成本。你可以改变你计算长度的位置,你可以计算,这比计算速度要快很多。
public static int getBinaryValue(String sequence){
int value = 1; //have another glance at this line!
for(int i = 0, n=sequence.length(); i < n; i++){
//I declared a variable 'n' in the initialisation, this means its only
//checked once, rather than being checked every time
if(sequence.charAt(i) == '1')
value += 1 << i;
//and here I've bitshifted the value. Basically I've said "take
//the number one and then shift it left down an imaginary binary
//track i times". So if i is three, for example, it'll shift it
//from 00000001 to 00000010 to 00000100 to 00001000, which is 8
//2^3 = 8
}
return value;
}
来源
2017-08-04 06:12:09
MrB
这就是Java的方式... – WizardWy
试试这个:的Integer.parseInt(binaryString,2) – subro
你可以使用的Integer.parseInt(序列,2); ...第二个参数是对的基础转换二进制它是2 ... – 100rabh