一、题目一
1. 题目描述
从输入任意个整型数,统计其中的负数个数并求所有非负数的平均值,结果保留一位小数,如果没有非负数,则平均值为0
本题有多组输入数据,输入到文件末尾,请使用while(cin>>)读入
输入描述:
输入任意个整数
输出描述:
输出负数个数以及所有非负数的平均值
输入
-13
-4
-7
输出
3
0.0
答案:
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String s = scanner.nextLine();
statistical(s);
}
}
private static void statistical(String s){
String[] split = s.split(" ");
//正数和
int count = 0;
//负数个数
int num = 0;
//个数
int length = split.length;
for (int i = 0; i < length; i++) {
int integer = Integer.valueOf(split[i]);
if(integer >= 0){
count += integer;
}else {
num++;
}
}
System.out.println(num);
System.out.println(new BigDecimal((double) count/(length-num)).setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue());
}
}
二、题目二
题目描述
连续输入字符串(输出次数为N,字符串长度小于100),请按长度为8拆分每个字符串后输出到新的字符串数组,
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
首先输入一个整数,为要输入的字符串个数。
例如:
输入:
2
abc
12345789
输出:
abc00000
12345678
90000000
答案:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int anInt = scanner.nextInt();
List<String> strs = new ArrayList<>();
for (int i = 0; i <= anInt ; i++) {
String s = scanner.nextLine();
if(null !=s && !"".equals(s)){
strs.add(s);
}
}
handle(strs);
}
}
private static void handle(List<String> toBeHandle){
toBeHandle.stream().forEach(s -> {
int length = s.length();
int a = length /8;
int b = 8 - length % 8;
String str = "";
for (int i = 0; i <= a; i++) {
if(i == a){
str = s.substring(8*i);
for (int j = 0; j < b && b != 8; j++) {
str += 0;
}
System.out.println(str);
}else {
str = s.substring(i * 8, (i + 1) * 8);
System.out.println(str);
}
}
});
}
三、题目三
题目描述
Redraiment是走梅花桩的高手。Redraiment总是起点不限,从前到后,往高的桩子走,但走的步数最多,不知道为什么?你能替Redraiment研究他最多走的步数吗?
样例输入
6
2 5 1 5 4 5
样例输出
3
提示
Example:
- 6个点的高度各为 2 5 1 5 4 5
- 如从第1格开始走,最多为3步, 2 4 5
- 从第2格开始走,最多只有1步,5
- 而从第3格开始走最多有3步,1 4 5
- 从第5格开始走最多有2步,4 5
所以这个结果是3。
答案:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String input;
while ((input = read.readLine())!=null){
int num = Integer.parseInt(input);
String[] strs = read.readLine().split(" ");
int[] nums = new int[num];
int max = 0;
for(int i=0;i<strs.length;i++){
nums[i] = Integer.parseInt(strs[i]);
}
int[] result = new int[num];
for(int i =0; i<nums.length;i++){
result[i]=1;
for(int j = 0;j<i;j++){
//如果nums[j]<nums[i]
if(nums[j]<nums[i]){
result[i]=Math.max(result[i],result[j]+1);
}
}
}
max = 1;
for(int i=0;i<result.length;i++){
if(result[i]>max){
max=result[i];
}
}
System.out.println(max);
}
}
}