题解 | #记负均正II#

记负均正II

http://www.nowcoder.com/practice/64f6f222499c4c94b338e588592b6a62

  • 我用的正则匹配所有负数,再将其替换为空,切割为数组。
  • 再将数组长度相减获取负数个数,最后进行相加计算。

import java.util.*;

public class Main {


    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        StringBuilder numStr = new StringBuilder();
        while (s.hasNextLine()){
            String num = s.nextLine();
            if ("".equals(num)) break;
            numStr.append(num+",");
        }
        String arrStr = numStr.toString();
        String res = arrStr.replaceAll("(-[0-9]+,)", "");
        String[] oldArr = arrStr.split(",");
        String[] resArr = res.split(",");
        int resCount = "".equals(resArr[0]) ? 0 : resArr.length;
        // 获取负数值
        System.out.println(oldArr.length - resCount);
        double count = 0;
        for (String num : resArr) {
            if("".equals(num)) continue;
            count += Integer.valueOf(num);
        }
        System.out.println(String.format("%.1f",count/resArr.length));
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务