2005 Challenge Problem #2


Inside a computer, everything is represented with binary numbers. This problem deals with the
usual convention for representing non-negative integers in binary. Each bit position represents
a certain power of 2. The rightmost position represents 20 = 1. The second position from the right
represents 21 = 2. The third position from the right represents 22 = 4, and so on. The overall number
that is represented is obtained by adding up some of these powers of 2 using the following rule:
If the binary number has a 1 in that position, we include the corresponding power of 2 in the sum,
and if the binary number has a 0 in that position, we don't.
(This is easier than it sounds.)

For example,

1011 = 23 + 21 + 20 = 8 + 2 + 1 = 11

0110101 = 25 + 24 + 22 + 20 = 32 + 16 + 4 + 1 = 53

Your challenge is to write a method toNonNegInt that takes as a parameter a String containing only
the characters '0' and '1' and returns the non-negative integer that it represents. If the actual parameter
passed to the method is null, or if the String contains any characters other than '0' and '1', return -1.

Restriction: You are only allowed to use two methods in the String class, namely length and charAt.


public int toNonNegInt(String binNum)
{
    // fill in here
}