【问题标题】:Converting String of binary digits to decimal number... using recursion将二进制数字字符串转换为十进制数...使用递归
【发布时间】:2015-06-14 07:38:04
【问题描述】:

Comp sci 教授在我们的作业中给了我们这个问题...我不确定如何继续,我编写的代码似乎失败得很惨。提示如下:


(binary to decimal) 编写一个递归方法,将二进制数作为字符串解析为十进制整数。方法头是:

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 "";
    }
}

【问题讨论】:

  • 看起来你快到了,但为了简化,我只需查看字符串的最后一位数字,然后将一个新的新字符串传递给bin2Dec,它是in 字符串的子字符串.即不需要index
  • 你得到什么输出或错误?

标签: java string recursion binary decimal


【解决方案1】:

没有额外的变量 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' 转换为各自数字的最佳方法。

【讨论】:

  • 这非常有效。起初在遵循此代码时遇到了一些麻烦,但这对我理解如何压缩/压缩代码有很大帮助。再次感谢您的提示。
【解决方案2】:

首先:您在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);
}

【讨论】:

    【解决方案3】:

    首先,定义一个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 的长度(减去该位置并减一,因为Java 使用从零开始的索引)。然后递归将该值添加到返回值。最后,public 方法只是

    public static int bin2Dec(String in) {
        return bin2Dec(in, 0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      相关资源
      最近更新 更多