Given an input, I'm trying to write a program to find the minimum base that can be associated with that number. For example the minimum base associated with 385 is base-9 (as it needs to have a base that supports the digit 8 which is its highest value digit). Similarly, the minimum base associated with B95 is base-12, since it uses 0 -9 and A and B.
This is my code
public static int findBase(String str){
int max = 0;
char c;
for (int i = 0; i <str.length() ; i++) {
c = str.toUpperCase().charAt(i);
if (Character.isDigit(c) && c > max) {
max = c;
}else if (Character.isLetter(c)) {
max = 10 + (c - 'A');
}
}
return max + 1;
}
The problem is that the function is returning random values.For example for the value 385 it returns 56. What am I doing wrong?
The problem is that you're using the unicode value of the character when it's a digit.
Instead of:
max = c;
... you should use:
max = c - '0';
Also note that Character.isLetter
returns true
for all unicode letters, including Arabic letters and letters from other alphabets, that have much higher unicode codepoint values; likewise for Character.isDigit
In your case, you're only capable of handling Latin characters from the ASCII character set, so to be safe it's better to check for that specifically. And you're not checking correctly for the maximum value (you're comparing the unicode codepoint to the max, not the converted value)
int v = 0;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'Z') {
v = 10 + (c - 'A');
}
if (v > max) {
max = v;
}
Full program:
public static int findBase(String str) {
int max = 0;
str = str.toUpperCase();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int v = 0;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'Z') {
v = 10 + (c - 'A');
}
if (v > max) {
max = v;
}
}
return max + 1;
}