Nothing more to add than the title. Looking for code review, optimizations and best practices.
public final class BaseAdder {
private BaseAdder() { }
/**
* Given two numbers and their bases, adds the number
* and returns the result in the same base.
*
* This code supports max-base 26.
*
*
* @param num1 the first number to be added
* @param num2 the second number to be added
* @param base the base of the numbers
*/
public static String add (String num1, String num2, int base) {
if (base < 2) throw new IllegalArgumentException("The base should at least be 2. Input base is: " + base);
if (base > 26) throw new IllegalArgumentException("The base should be less than 26. Input base is: " + base);
/*
* http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java
* and StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required – Joel Dec 23 '09 at 8:52
*
*/
final StringBuilder stringBuilder = new StringBuilder();
int carry = 0;
for (int i = num1.length() - 1; i >= 0; i--) {
int x = getIntValue(num1.charAt(i), base) + getIntValue(num2.charAt(i), base) + carry;
if (x >= base) {
carry = 1;
x = x - base;
} else {
carry = 0;
}
stringBuilder.append(getCharValue(x, base));
}
if (carry == 1) stringBuilder.append(1);
return stringBuilder.reverse().toString();
}
public static int getIntValue(char ch, int base) {
if (ch > getCharValue(base - 1, base)) {
throw new IllegalArgumentException(" invalid character " + ch + " for input base " + base);
}
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
Character.toUpperCase(ch);
return ch - 'A' + 10;
}
public static char getCharValue(int x, int base) {
if (x >= base) {
throw new IllegalArgumentException(" invalid number " + x + " for input base " + base);
}
if (x >= 0 && x <= 9) {
return (char) (x + '0');
}
return (char)(x + 'A' - 10);
}
public static void main(String[] args) {
assertEquals("100", BaseAdder.add("10", "10", 2));
assertEquals("11", BaseAdder.add("10", "01", 2));
assertEquals("25", BaseAdder.add("10", "15", 10));
assertEquals("4A", BaseAdder.add("1C", "2D", 15));
assertEquals("1B9", BaseAdder.add("CC", "ED", 16));
assertEquals("1B", BaseAdder.add("C", "D", 14));
assertEquals("1A", BaseAdder.add("C", "D", 15));
assertEquals("19", BaseAdder.add("C", "D", 16));
}
}
}
at the very end (assuming everything already matches up). \$\endgroup\$