将String二进制转换为整数Java

时间:2016-02-24 14:39:43

标签: java algorithm

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

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

我解决问题的方法是:

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

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

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

我不明白他们的解决方案是如何运作的? 我已经调试但仍无法找到关键内容。谁能解释一下?

2 个答案:

答案 0 :(得分:5)

它们基本上将结果移位beta,如果设置了该位,则加1。

示例:01101

2 * result

就位而言:8 + 4 + 1 = 13

或者,您可以将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) 替换为result = result * 2,但在单个语句中添加1则不起作用。你可以写result <<= 1,但这比乘法更长,更难阅读。

答案 1 :(得分:2)

复制多项式定义 x = xn b ^ n + xn-1 b ^ n-1 + ... + x1 b ^ 1 + x0 b ^ 0 您可以将其重写为

x = ((((...(((( xn * b + xn-1 ) * b + ...  )* b + x1 ) * b + x0 

其中b = 2表示二进制表示,并且在最左侧有n-1个括号开头。

对于n = 4,这读起来像

x = ((((x3*2)+x2)*2+x1)*2+x0 = x3 * 2^3 + x2 * 2^2 + x1 * 2^1 + x0 * 2^0

如果要解析以MSB(x_n)开头的字符串朝向LSB(x_0),则在阅读x_i时必须执行

 result = result * 2 + x_i 

在执行此result之前,会存储值

((...(((( xn * b + xn-1 ) * b + ...  )* b + x_(i+1) )

执行此result后会存储值

((...(((( xn * b + xn-1 ) * b + ...  )* b + x_i )

通过归纳推理你可以证明你最终会计算出正确的答案。