Hello,
i have a problem with the exercise “All your base” in Java. I tested the code on my laptop in BlueJ and on exercism.org. On exercism i get a “tests timed out” message, in BlueJ it works and returns a correct array, atleast for the numbers i tested.
I am quite inexperienced, so any tipps on how to improve the code in general would be appreciated.
import java.util.List;
import java.util.ArrayList;class BaseConverter {
private final int _originalBase; private final int[] _originalDigits; /** * Constructor of class BaseConverter. * * @param originalBase original base of the number * @param originalDigits original digits of the number */ public BaseConverter(int originalBase, int[] originalDigits) { if (originalBase < 2) { throw new IllegalArgumentException("Bases must be at least 2."); } for (int i : originalDigits) { if (i >= originalBase) { throw new IllegalArgumentException("All digits must be strictly less than the base."); } else if (i < 0) { throw new IllegalArgumentException("Digits may not be negative."); } } _originalBase = originalBase; _originalDigits = originalDigits.clone(); } /** * Converts a number to a different base * * @param newBase new base to convert the number to * @return number in new base */ public int[] convertToBase(int newBase) { int baseTen = convertToTen(); return helpConvertToNewBase(baseTen, newBase); } private int convertToTen() { int tempTen = 0; for (int i = 0; i < _originalDigits.length; i++) { tempTen += (int) _originalDigits[i] * Math.pow(_originalBase, _originalDigits.length - i - 1); } return tempTen; } private int[] helpConvertToNewBase(int numberToConvert, int newerBase) { List<Integer> newBaseNumber = new ArrayList<Integer>(); while (numberToConvert != 0) { newBaseNumber.add(0 ,numberToConvert % newerBase); numberToConvert = numberToConvert / newerBase; } return convertListToArray(newBaseNumber); } private int[] convertListToArray(List<Integer> listToConvert) { int[] convertedList = new int[listToConvert.size()]; for (int i = 0; i < listToConvert.size(); i++) { convertedList[i] = listToConvert.get(i); } return convertedList; }
}