1

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()

4
  • This homework problem clearly requires addition. Can you use arrays or lists? Is the input string a fixed length? Commented Jan 27, 2016 at 16:45
  • Yes, it does allow addition and subtract. No you cannot use array or lists. only Integer and String with charAt(), length(), and equals. Commented Jan 27, 2016 at 16:48
  • What about input length? Is it fixed input length, is there variability within a range, or is it potentially infinitely long? Commented Jan 27, 2016 at 16:52
  • it is a fixed length . E.g ("1111" ==> 15) Commented Jan 27, 2016 at 16:54

4 Answers 4

2

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

if(b.charAt(z).equals('1'){ is missing a closing parenthesis and doesn't work - the primitive type char doesn't have an equals method!
1

Use the Integer.valueOf(String, int) method:

Integer.valueOf('10101',2)

Comments

1

Try to use Integer.parseInt(..) like this:

  int value = Integer.parseInt(b, 2);

Ofcourse b is a binary String.

1 Comment

b.toCharArray()[i] is the wasteful version of b.charAt(i)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.