/** * COMP 1711 (Fall 2005) * * Solution to Challenge Problem #2 (Binary Strings) * * The method in this class converts binary strings into non-negative integers. * * @author Based on a solution by Geoffrey Bouchard * @version Dec-08-2003 */ public class Problem02 { // Behaviour is same as for problem description, except also returns -1 // for a non-null empty String public static int toNonNegInt(String binNum) { if ((binNum == null) || (binNum.equals(""))) { return -1; } // end if // Return -1 if any character in String is NOT '0' or '1' for (int i=0; i < binNum.length(); i++) { if ((binNum.charAt(i)!='0') && (binNum.charAt(i)!='1')) { return -1; } // end if } // end for int integer = 0; // Holds the answer double exp = 0.0; // Needed for the power function. for (int i = binNum.length()-1; i >= 0; i--) { if (binNum.charAt(i) == '1') { integer += (int) Math.pow(2.0, exp); } // end if exp++; } //end for return integer; } // end toNonNegInt(String) } // end class Problem02