[英]Converting String of binary digits to decimal number… using recursion
Comp sci教授在我们的作业中给了我们这个问题...我不知道如何继续,我写的代码似乎失败了。 这是提示:
(二进制到十进制)编写一个递归方法,将二进制数作为字符串解析为十进制整数。 方法标题是:
public static String bin2Dec(String binaryString)
编写一个测试程序,提示用户输入二进制字符串并显示其十进制等效值。
任何帮助非常感谢。 这是我的代码如下:
import java.util.Scanner;
public class HW04_P5 {
static int index = 0;
static int power = 0;
static int number = 0;
static boolean exit = false;
@SuppressWarnings("resource")
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print(" Enter a binary number to convert to decimal: ");
String in = scan.nextLine();
index = in.length()-1;
System.out.print(" Binary number converted to decimal: "+bin2Dec(in));
}
public static String bin2Dec(String in)
{
if((in.substring(index,index+1).equals("1"))&&(index>0))
{
number += Math.pow(2,power);
System.out.print(number);
power++;
index--;
bin2Dec(in);
}
else if((in.substring(index,index+1).equals("0"))&&(index>0))
{
power++;
index--;
bin2Dec(in);
}
System.out.print(number);
return "";
}
}
没有额外的变量index,power和p更清洁。 只需从右到左处理字符串。 您也不希望在递归函数之外跟踪“全局”变量号...这令人困惑和奇怪。 在我看来,你希望所有的状态都包含在递归函数中。 即使有这些限制,您仍然可以在两行中完成:
public static int bin2Dec(String s) {
if (s == null || s.isEmpty()) return 0;
else return s.charAt(s.length()-1)-48+2*bin2Dec(s.substring(0,s.length()-1));
}
这可能不是最清晰的解决方案,但我认为它是最优雅的。 通过将else子句分成几行可以提高清晰度。 48是0的Unicode字符编号,这可能不是将字符“0”和“1”转换为各自编号的最佳方法。
第一:您在if
条件下打印数字,也没有\\n
。 您获得的输出将在多个调用中打印数字。
其次,条件index > 0
应该是index >= 0
,否则你将错过第0个索引的测试。 而且这个条件应该在&&
之前,而不是之后。
第三,从方法中返回number
,而不是在那里打印。
以下是带有上述更改的修改方法:
public static String bin2Dec(String in) {
if ((index >= 0) && (in.substring(index, index + 1).equals("1"))) {
number += Math.pow(2, power);
power++;
index--;
bin2Dec(in);
} else if ((index >= 0) && (in.substring(index, index + 1).equals("0"))) {
power++;
index--;
bin2Dec(in);
}
return "" + number;
}
但是,我仍然看到很多重复。 你可以使用String#charAt()
方法,而不是substring()
,因为你真的要检查单个字符。 这是您的方法的简化版本:
public static String bin2Dec(String in) {
if (index < 0) {
return "" + number;
}
if (in.charAt(index) == '1') {
number += Math.pow(2, power);
}
power++;
index--;
return bin2Dec(in);
}
首先,定义一个也采用类似位置的private
版本
private static int bin2Dec(String in, int p) {
if (in == null || in.isEmpty() || p >= in.length()) {
return 0;
}
int s = (in.charAt(p) == '1' ? 1 : 0) << in.length() - p - 1;
return s + bin2Dec(in, p + 1);
}
请注意,我们首先定义一个停止条件,然后确定该位置的字符是否为1
,然后向左移动String
的长度(减去该位置减去1,因为Java使用基于零的索引)。 然后递归将该值添加到返回值。 最后, public
方法是公正的
public static int bin2Dec(String in) {
return bin2Dec(in, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.