我需要使用递归,但我似乎无法弄清楚。我需要创建一个方法来调用将二进制字符串转换为整数十进制形式。我只需要通过递归来做到这一点。这意味着没有全局变量或循环。这是我所拥有的:
public class Practice {
public static void main( String[] args ) {
if( convert( "1010111" ) == 57) {
System.out.println( "test worked: 57" );
}
if( convert( "1110001" ) == 113) {
System.out.println( "test worked: 113" );
}
}
public static int convert( String temp ) {
Integer.parseInt(temp);
if(Integer.parseInt(temp)>0) {
return 0;
}
return temp/%100 + convert(temp*2)
}
}
}
输出:
测试成功:57
测试成功:113
如果您需要使用递归(作为作业或练习),您可以考虑以下方法:
伪代码:
int convert(String input) {
if input is empty {
return 0;
}
else {
int lastDigit = last digit of input
String prefix = input excluding last digit
int result = convert(prefix) * 2 + lastDigit
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句