【问题标题】:How to define an exponent as the index position of a string如何将指数定义为字符串的索引位置
【发布时间】:2014-10-01 01:05:09
【问题描述】:

我正在尝试创建一个将二进制数转换为以 10 为基数的 int 方法。我认为我的循环结构正确,但我不知道如何将索引位置与指数相关联。基本上,如果字符串中有一个“1”,我想将它作为 2 返回到该字符的索引位置的幂。此外,这将需要我反转索引(以便 0 位置是字符串的最右边的字符。这是我到目前为止所拥有的:

public static int BinaryToNumber(String numberInput)
{
    int len = numberInput.length();

    for(int i=len-1; i<len; i--)
    {
        if(i == '1');
        {
            return n;
        }
    }
    return 0; 
}

提前谢谢你!

【问题讨论】:

标签: java eclipse variables char int


【解决方案1】:

如果可能,我更喜欢 Java 内置例程 - 正如我在评论 Integer.parseInt(numberInput, 2); 中所说。按照惯例,Java 方法名称以小写字母开头。最后,你可以修复你的代码(我添加了一个小测试工具),比如,

public static int binaryToNumber(String numberInput) {
    if (numberInput == null) {
        return 0;
    }
    int ret = 0;
    char[] ni = numberInput.trim().toCharArray();
    for (int i = 0; i < ni.length; i++) {
        if (ni[i] == '1') {
            // This is 2 ^ (n) where (n) is based on the position from the right.
            ret += 1 << ni.length - i - 1;
        }
    }
    return ret;
}

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        String t = Integer.toBinaryString(i);
        System.out.printf("%s = %d%n", t, binaryToNumber(t));
    }
}

【讨论】:

    【解决方案2】:

    这是我解决问题的方法

    public static void main(String[] args) {
        String str = "100101";
        System.out.println(toDecimal(str));
    }
    
    private static int toDecimal(String binary) {
        int result = 0;
        for(int i = 0; i < binary.length(); i++) {
            int a = (int) binary.charAt(i) - 48;
            double secondPart = 1 << (binary.length()-1) - i;
            result +=  a * secondPart;
        }
    
        return result;
    }
    

    希望对你有帮助
    萨拉姆

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 2019-07-22
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多