While reading this book I came across converting binary to integer. The code that is given by the book is:
// 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;
}
and the way I solved the problem is:
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;
}
I know my code has an extra counter and it is probably a bit slowly but the way I implement the solution is by following the polynomial definition
x = xn b^n + xn-1 b^n-1 + ... + x1 b^1 + x0 b^0.
What I don't understand is how their's solution works ? I've already debugged but still can't find what is key. Can someone explain ?
Integer.parseInt(s, 2)? They simply set each "bit" of theintmanually, so either1or0and bitshift.elsecase which probably should be used to detect non-binary strings, i.e. characters that aren't 0 or 1.