Reputation: 365
How can I do this without using multiplication, division or mod?
I come with the solution but it needs multiplication.
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
value = value * 2 + (int)b.charAt(i) - 48;
}
}
EDIT: SORRY! Only 3 java API are allowed. length(), charAt(), and equals()
Upvotes: 1
Views: 121
Reputation: 780
You can use the method Integer.parseInt
to do this.
String binary = "101010"
int value = Integer.parseInt(binary, 2);
The '2' in Integer.parseInt
means to parse the String
in base 2.
Upvotes: 0
Reputation: 8387
Try to use Integer.parseInt(..)
like this:
int value = Integer.parseInt(b, 2);
Ofcourse b
is a binary String.
Upvotes: 1
Reputation: 577
Without multiplication, use bitwise shift operator:
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
if(b.charAt(z) == '1'){
shift = b.length()-z-1;
value += (1 << shift);
}
}
}
Upvotes: 2
Reputation: 13984
Use the Integer.valueOf(String, int)
method:
Integer.valueOf('10101',2)
Upvotes: 1