将String二进制转换为整数Java

Ade*_*lin 0 java algorithm

在阅读本书时,我遇到了将二进制转换为整数的问题.这本书给出的代码是:

 // convert a String of 0's and 1's into an integer
    public static int fromBinaryString(String s) {
       int result = 0;
       for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);
          if      (c == '0') result = 2 * result;
          else if (c == '1') result = 2 * result + 1;
       }
       return result;
    }
Run Code Online (Sandbox Code Playgroud)

我解决问题的方法是:

public static int fromBinary(String s) {
        int result = 0;
        int powerOfTwo = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if ('1' == s.charAt(i)) {
                result += Math.pow(2, powerOfTwo);
            }
            powerOfTwo++;
        }
 return result;
    }
Run Code Online (Sandbox Code Playgroud)

我知道我的代码有一个额外的计数器,它可能有点慢,但我实现解决方案的方法是遵循多项式定义

x = xn b ^ n + xn-1 b ^ n-1 + ... + x1 b ^ 1 + x0 b ^ 0.

我不明白他们的解决方案是如何运作的?我已经调试但仍然找不到什么是关键.谁能解释一下?

Tho*_*mas 5

它们基本上将结果移位,2 * result如果该位置位则加1.

示例:01101

1. iteration: result = 0 -> result * 2 = 0      (same as binary 00000)
2. iteration: result = 0 -> result * 2 + 1 = 1  (same as binary 00001)
3. iteration: result = 1 -> result * 2 + 1 = 3  (same as binary 00011)  
4. iteration: result = 3 -> result * 2 = 6      (same as binary 00110)
5. iteration: result = 6 -> result * 2 + 1 = 13 (same as binary 01101)
Run Code Online (Sandbox Code Playgroud)

在比特方面:8 + 4 + 1 = 13

或者你可以替换为result = result * 2,result <<= 1但在单个语句中添加1将不起作用.你可以写,result = (result << 1) + 1但这比乘法更长,更难阅读.