【问题标题】:Why doesn't my octal-to-decimal converter work for certain cases?为什么我的八进制到十进制转换器在某些情况下不起作用?
【发布时间】:2015-11-17 09:48:40
【问题描述】:

我正在研究这个八进制到十进制的转换器:

public int getDecimal(String input)
{
    int output = 0;

    // reverse input so that it is easier to work with
    input = new StringBuilder(input).reverse().toString();

    for (int c = 0; c < input.length(); c++)
    {
        // check for invalid digit
        if (input.charAt(c) < '0' || input.charAt(c) > '7')
            return 0;

        if (input.charAt(c) != '0')
        {
            if (input.charAt(c) == '1')
                output += Math.pow(8, c);
            else // if it's greater than 1
                output += Math.pow(8, c) + input.charAt(c) - 1;
        }
    }

    return output;
}

它适用于大约 65% 的测试用例,例如将“10”转换为“8”。但是,它不适用于其他情况,例如将“17”转换为“15”。我做错了什么?

【问题讨论】:

  • 您的方法似乎没有采用input 参数。
  • 要获得 8^c,请使用 1 &lt;&lt; (c*3) 而不是 pow,这要慢得多
  • 我的方法现在有一个input 参数。

标签: java binary octal


【解决方案1】:

你的公式是错误的。

你在这条线上做什么,

output += Math.pow(8, c) + input.charAt(c) - 1;

应该更像,

output += Math.pow(8, c) * (input.charAt(c) - '0');

喜欢,output += 8^(index) * digit

【讨论】:

    【解决方案2】:

    您需要记住“17”的含义:1 * 8 + 7。您的算法是错误的。您不需要反转字符串。对于循环中的每次迭代,只需将前一个 output 值乘以基数(在本例中为 8)并添加下一个数字的值。继续直到字符串结束。

    【讨论】:

      【解决方案3】:

      你也可以试试这个,不需要反转字符串:

      public static int getDecimal() {
          int output = 0;
          String input="17"; //by example
          int c=input.length();
          int i=0;
          while(c > 0) {
              if (input.charAt(i) < '0' || input.charAt(i) > '7') {
                  return 0;
              }
              output += Math.pow(8, c-1) * Integer.parseInt(input.charAt(i++)+"");
              c--;
          }
          return output;
      }
      

      【讨论】:

        【解决方案4】:

        你可以用这个:

        input = new StringBuilder(input).reverse().toString();
        
        System.out.println("input:"+input);
        
        for (int c = 0; c < input.length(); c++) {
            output += Integer.parseInt(input.charAt(c) + "") * Math.pow(8, c);
        
            System.out.println("output:" + output);
        }
        

        【讨论】:

          【解决方案5】:
          if (input.charAt(c) != '0')
          {
              if (input.charAt(c) == '1')
                  output += Math.pow(8, c);
              else // if it's greater than 1
                  output += Math.pow(8, c) + input.charAt(c) - 1;
          }
          

          这里至少有两个错误。您可以将这一切简化为

          output = output*8+input.charAt(c)-'0';
          

          摆脱倒车步骤后。不用担心 0 和 1 的特殊情况。

          【讨论】:

            猜你喜欢
            • 2020-12-07
            • 2015-06-09
            • 2011-02-06
            • 1970-01-01
            • 1970-01-01
            • 2011-08-21
            • 1970-01-01
            • 2013-11-26
            • 2012-10-20
            相关资源
            最近更新 更多