题目: 在一串空格分隔的数字中,你要返回最高和最低的数字。
案例:
HighAndLow("1 2 3 4 5") // return"5 1"
HighAndLow("1 2 -3 4 5")// return"5 -3"
HighAndLow("1 9 3 4- 5")// return"9-5"
解答:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Kata {
//我自己解答的
public static String HighAndLow1(String numbers) {
String[] str = numbers.split(" ");
List<Integer> li = new ArrayList<Integer>();
for (int i = 0; i < str.length; i++) {
li.add(Integer.parseInt(str[i]));
}
Collections.sort(li);
int low = li.get(0);
int high = li.get(li.size() - 1);
return high + " " + low;
}
//参考网友的
public static String HighAndLow2(String numbers) {
int min = Arrays.stream(numbers.split(" ")).mapToInt(i -> Integer.parseInt(i)).min().getAsInt();
int max = Arrays.stream(numbers.split(" ")).mapToInt(i -> Integer.parseInt(i)).max().getAsInt();
return String.format("%d %d", max, min);
}
//参考网友的
public static String HighAndLow3(String numbers) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
String nums[] = numbers.split(" ");
for (String s : nums) {
int num = Integer.parseInt(s);
max = Math.max(max, num);
min = Math.min(min, num);
}
return "" + max + " " + min;
}
public static void main(String[] args) {
System.out.println(HighAndLow1("1 2 3 4 5"));
System.out.println(HighAndLow2("1 2 3 4 5"));
System.out.println(HighAndLow3("1 2 3 4 5"));
}
}