![](/img/trans.png)
[英]Unable to convert binary string to integer despite using parseInt in java
[英]Convert String binary to integer Java
在閱讀本書時,我遇到了將二進制轉換為整數的情況。 本書給出的代碼是:
// 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 * result
,如果該位置1,則加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)
以位為單位:8 + 4 + 1 = 13
或者,您可以將result = result * 2
替換為result <<= 1
但是在單個語句中添加1則無法使用。 您可以寫出result = (result << 1) + 1
但是比乘法更長,更難讀。
復制多項式定義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 )
通過歸納推理,您可以證明自己最終算出了正確的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.