Java 与数字相关联的最小基数
给定一个输入,我正试图编写一个程序,以找到与该数字相关联的最小基数。例如,与385关联的最小基数是base-9(因为它需要有一个支持数字8的基数,数字8是它的最高值数字)。类似地,与B95相关联的最小基数是base-12,因为它使用0-9以及A和B 这是我的密码Java 与数字相关联的最小基数,java,algorithm,base,Java,Algorithm,Base,给定一个输入,我正试图编写一个程序,以找到与该数字相关联的最小基数。例如,与385关联的最小基数是base-9(因为它需要有一个支持数字8的基数,数字8是它的最高值数字)。类似地,与B95相关联的最小基数是base-12,因为它使用0-9以及A和B 这是我的密码 public static int findBase(String str){ int max = 0; char c; for (int i = 0; i &l
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;
}
publicstaticintfindbase(stringstr){
int max=0;
字符c;
对于(int i=0;i max){
max=c;
}else if(字符号:c)){
最大值=10+(c-‘A’);
}
}
返回最大值+1;
}
问题是函数返回的是随机值。例如,对于值385,它返回56。我做错了什么?问题是,当字符是数字时,您使用的是字符的unicode值 而不是:
max = c;
。。。你应使用:
max = c - '0';
还要注意,Character.isleter
返回所有unicode字母的true
,包括阿拉伯文字母和其他字母表中的字母,这些字母具有更高的unicode码点值;同样适用于Character.isDigit
在您的情况下,您只能处理ASCII字符集中的拉丁字符,因此为了安全起见,最好专门检查一下。
并且您没有正确检查最大值(您将unicode代码点与最大值进行比较,而不是转换后的值)
intv=0;
如果(c>='0'&&c='A'&&c最大值){
最大值=v;
}
完整程序:
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;
}
publicstaticintfindbase(stringstr){
int max=0;
str=str.toUpperCase();
对于(int i=0;i='0'&&c='A'&&c最大值){
最大值=v;
}
}
返回最大值+1;
}
我尝试了这一点,但在385中我得到了6。它应该返回9。仍然不明白代码出了什么问题。您对最大值的检查是比较unicode代码点值和最大值,而不是转换后的值。你没有对照max检查字母。如果最大数字值是9
,那么它的基数是10(因为0
也是一个有效值),所以当我合并所有这些时,你需要返回max+1
,结果是9
输入“385”
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;
}