zoukankan      html  css  js  c++  java
  • Codewars Solution:Count of positives / sum of negatives

    Level 8kyu :Count of positives / sum of negatives

    给定一个整数数组。

    返回一个数组,其中第一个元素是正数的计数,第二个元素是负数的总和。

    如果输入数组为空或为null,则返回一个空数组

    对于输入[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15],您应该返回[10, -65]

     1 public class Kata
     2 {
     3     public static int[] countPositivesSumNegatives(int[] input)
     4     {
     5       int[] result=new int[2];//定义返回数组
     6       int[] empty={};//定义返回空数组
     7       if(input==null||input.length==0)
     8         return empty; //return an array with count of positives and sum of negatives
     9       else{
    10         int count=0;
    11         int sum=0;
    12         for(int i=0;i<input.length;i++){
    13           if(input[i]>0){
    14             count++;
    15           }else if(input[i]<0){
    16             sum+=input[i];
    17           }
    18         }
    19         result[0]=count;
    20         result[1]=sum;
    21       }
    22       return result;
    23     }
    24 }

     他人解决方案(精简):

     1 public static int[] countPositivesSumNegatives(int[] input)
     2 {
     3     if (input == null || input.length == 0) return new int[] {};
     4     int count = 0,sum = 0;
     5     for (int i : input) {
     6        if (i > 0) count ++;
     7        if (i < 0) sum += i;
     8      }
     9      return new int[] {count,sum};
    10 }
  • 相关阅读:
    杨辉三角
    手动实现md5加密
    戳气球
    重构字符串
    四数相加 II
    背包问题 II
    组合总和 IV
    背包问题 V
    背包问题
    Win 10安装Python及环境变量配置
  • 原文地址:https://www.cnblogs.com/mc-web/p/12940466.html
Copyright © 2011-2022 走看看