题解 | #记负均正#

记负均正

https://www.nowcoder.com/practice/6abde6ffcc354ea1a8333836bd6876b8

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String a;
        int[] numbers;
        int n = 0, i = 0, l, negCnt = 0;
        float sum = 0;
        try {
            a = in.readLine();
            n = parse1(a);
            numbers = new int[n];
            a = in.readLine();
            parse2(a, numbers);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        l = numbers.length;
        while (i < l) {
            if (numbers[i] < 0)
                negCnt++;
            else if (numbers[i] == 0) {
                n--;
            } else {
                sum += numbers[i];
            }
            i++;
        }
        n -= negCnt;
        System.out.print(negCnt + " "
						 + (n == 0 ? "0.0" : Math.round(sum * 10 / n) / 10f));//先乘10取整,后除10
    }

    public static int parse1(String a) {
        int i = 0, l = a.length(), n = 0;
        char[] chrAy = new char[l];
        a.getChars(0, l, chrAy, 0);
        while (i < l) {
            if ((chrAy[i] - '0' | '9' - chrAy[i]) > 0) {
                n *= 10;
                n += chrAy[i] - '0';
            }
            i++;
        }
        return n;
    }

    public static void parse2(String a, int[] arr) {
        int i = 0, j = 0, l = a.length(), n = 0;
        boolean negative = false;
        char[] chrAy = new char[l];
        a.getChars(0, l, chrAy, 0);
        while (i < l) {
            if (chrAy[i] == ' ') {
                if (negative)
                    n = -n;
                arr[j++] = n;
                negative = false;
                n = 0;
            } else if (chrAy[i] == '-')
                negative = true;
            else {
                n *= 10;
                n += chrAy[i] - '0';
                if (i == l - 1) {
                    if (negative)
                        n = -n;
                    arr[j] = n;
                }
            }
            i++;
        }
    }
}

全部评论

相关推荐

05-07 19:10
已编辑
中国科学技术大学 C++
silly01:现在先去 momenta,8-9月去鹅找日常实习,八股文算法背好了你这随便进。不过建议补充一下后端知识,MySQL、Redis看下八股,再补个6824,加点go后台的技术栈,9月随便进大厂。CPP后端只能来WXG
点赞 评论 收藏
分享
04-27 08:59
常州大学 Java
牛客139242382号:《两门以上汇编语言》
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务