我刚刚完成了一个关于Kattis的问题"一个理性序列2"并想知道是否有更有效的方法可以将二进制数转换为十进制数。这是我的代码:
public static int getDecimalValue(String sequence){
int value = 1;
for(int i = 0; i < sequence.length(); i++){
if(sequence.charAt(i) == '1')
value += (int)Math.pow(2, i);
}
return value;
}
任何帮助都会很棒!
答案 0 :(得分:0)
int value = Integer.parseInt(sequence,2);
答案 1 :(得分:0)
有几点。首先,你的代码实际上是一个错误 - 尝试传递它00000000(8个零)并看看会发生什么。
至于效率,你可以节省几笔钱。你可以改变你计算长度的位置,你可以bitshift计算,这要快得多。
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;
}