0
\$\begingroup\$

Problem

  • Implement a base N to base 10 (decimal) converter, where N is between 2 and 36 inclusive.

Implementation

  • Am I over-complicating things in calculateDecimalCharacterValue?
public class BaseToDecimalConverter {

  public static int convertToDecimal(int base, String input) {
    if (base < 2) {
      throw new IllegalArgumentException();
    }

    if (base > 36) {
      throw new IllegalArgumentException();
    }

    if (input == null) {
      throw new IllegalArgumentException();
    }

    int length = input.length();
    int sum = 0;
    for (int i = 0; i < length; i++) {
      int digitValue = calculateDecimalCharacterValue(input.charAt(i), base);
      sum += digitValue * Math.pow(base, length - 1 - i);
    }

    return sum;
  }

  public static int calculateDecimalCharacterValue(char c, int base) {
    if (base < 2) {
      throw new IllegalArgumentException();
    }

    if (base > 36) {
      throw new IllegalArgumentException();
    }

    if (Character.isDigit(c)) {
      int numericValue = Character.getNumericValue(c);
      if (numericValue < 0) {
        throw new IllegalArgumentException();
      }
      return numericValue;
    }

    if (Character.isAlphabetic(c) && base > 10) {
      int alphabetValue = Character.toUpperCase(c) - 'A' + 10;
      if (alphabetValue > base) {
        throw new IllegalArgumentException();
      }
      return alphabetValue;
    }

    throw new IllegalArgumentException();
  }
}
\$\endgroup\$
3
\$\begingroup\$

It's weird that you offer two public functions: a general-purpose convertToDecimal(), and a calculateDecimalCharacterValue() that does the same thing but with more restrictive validation. The latter should be a private helper function.

You are over-complicating things by a lot: the whole thing could be accomplished with Integer.parseInt(s, radix). And — not that you would need it — calculateDecimalCharacterValue(c, base) could be done using Character.digit(ch, radix).

Technically, you aren't converting to and from decimal (base ten). You are parsing numbers in a base-N representation to an int; it just happens that ints are conventionally formatted in base ten when you do things like System.out.println(). So, the function names aren't quite right.

You shouldn't need to use Math.pow(). The usual algorithm goes like this:

public static int convertFromBase(int base, String input) {
    // Validation omitted here...

    int result = 0;
    for (char c : input.toCharArray()) {
        result = result * base + Character.digit(c, base);
    }
    return result;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.