카타 8급 Count of positives / sum of negatives

Jmnote (토론 | 기여)님의 2019년 4월 15일 (월) 01:42 판 (→‎PHP)

1 C

#include <stddef.h>
void count_positives_sum_negatives(
  int *values, size_t count, int *positivesCount, int *negativesSum) {
  for(int i = 0; i < count; i ++) {
    if(values[i] > 0) *positivesCount += 1;
    else  *negativesSum += values[i];
  }
}
#include <stddef.h>
void count_positives_sum_negatives(
  int *values, size_t count, int *positivesCount, int *negativesSum) {
  int posCount = 0; 
  int negSum = 0;
  for(int i=0; i<count; i++) {
    if( values[i]>0 ) posCount++;
    else negSum += values[i];
  }
  *positivesCount = posCount;
  *negativesSum = negSum;
}

2 C++

#include <vector>

std::vector<int> countPositivesSumNegatives(std::vector<int> input)
{
    if(input.empty()) return {};
    int posCnt=0, negSum=0;
    for(int x: input)
      x>0 ? posCnt++ : negSum+=x;
    return {posCnt, negSum};
}
#include <vector>

std::vector<int> countPositivesSumNegatives(std::vector<int> input)
{
    std::vector<int> res = {};
    if(input.empty()) return res;
    int posCnt=0, negSum=0;
    for(int num: input) {
      if(num>0) posCnt++;
      else negSum += num;
    }
    res.push_back(posCnt);
    res.push_back(negSum);
    return res;
}

3 Kotlin

4 PHP

function countPositivesSumNegatives($input) {
  if (empty($input)) return [];
  $posCount = $negSum = 0;
  foreach($input as $value) {
    if ($value > 0) $posCount++;
    else $negSum += $value;
  }
  return [$posCount, $negSum];
}
function countPositivesSumNegatives($input) {
  $count = count($input);
  if( $count < 1 ) return [];
  $posCount = 0;
  $negSum = 0;
  for($i=0; $i<$count; $i++) {
    if( $input[$i] > 0 ) $posCount++;
    else $negSum += $input[$i];
  }
  return [$posCount, $negSum];
}