[英]Find Max Number in String of Numbers
I have run into an interesting problem and wanted to know if anyone had any leads on how to solve it. 我遇到了一个有趣的问题,想知道是否有人有任何关于如何解决它的线索。 When given a string of numbers, I want to find the highest number.
当给出一串数字时,我想找到最高的数字。 So if the string is "2836", then the output should be 8, if the string is "12345" then the output should be 5 and so on.
因此,如果字符串是“2836”,则输出应为8,如果字符串为“12345”,则输出应为5,依此类推。 Here is the method I am working on:
这是我正在研究的方法:
public static void main(String[] args) {
max("215");
}
public static void max(String number) {
if (number.isEmpty()) {
System.out.println("The string is empty");
System.exit(0);
}
int compCount = 1;
int max = number.charAt(0);
int compare = number.charAt(compCount);
for (int i = 0; i < number.length(); i++) {
if (max > compare) {
compCount++;
} else if (compare > max) {
max = compare;
} else {
System.out.print(max);
}
}
System.out.print(max);
}
When this code executes it gives me 50 and I want 5 当这段代码执行时,它给了我50,我想要5
Well, you have a lot of wrong stuff going on. 好吧,你有很多错误的东西在继续。 Firstly , you never change
compare
, Second , you take the int
in ascii, and don't convert it to its Integer
representation. 首先 ,你永远不会改变
compare
, 其次 ,你在ascii中取int
,而不是将它转换为它的Integer
表示。 Thirdly , you need only one if
statement. 第三 ,您只需要一个
if
语句。 All combined, it gives 所有组合,它给出
int max = Character.getNumericValue(number.charAt(0));
for (int i = 1; i < number.length(); i++) {
int compare = Character.getNumericValue(number.charAt(i));
if (max < compare) {
max = compare;
}
}
return max;
I've used Character#getNumericValue to convert the char
to int
我使用Character#getNumericValue将
char
转换为int
Since ASCII codes of digits are sorted in ascending order you can easily do it with Java 8 like this: 由于ASCII数字代码按升序排序,因此可以使用Java 8轻松完成,如下所示:
public static void max(String number) {
if (number == null || number.isEmpty()) {
return;
}
int max = number.chars().max().getAsInt();
System.out.println(Character.getNumericValue((char) max));
}
If your input can has mix of digits and other symbols you also able to handle it: 如果您的输入可以混合数字和其他符号,您也可以处理它:
public static void max(String number) {
if (number == null || number.isEmpty()) {
return;
}
OptionalInt max = number.chars().filter(Character::isDigit).max();
if (max.isPresent()) {
System.out.println(Character.getNumericValue((char) max.getAsInt()));
} else {
System.err.println("Provided string doesn't contain digits");
}
}
you have to modify your max method as given below 你必须修改你的max方法,如下所示
public static void max(String number) {
if (number.isEmpty()) {
System.out.println("The string is empty");
System.exit(0);
}
int max = Integer.parseInt(number.charAt(0)+"");
for (int i = 1; i < number.length(); i++) {
int compare = Integer.parseInt(number.charAt(i)+"");
if (compare > max) {
max = compare;
}
}
System.out.print(max);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.