1 C[ | ]
C
Copy
#include <stddef.h>
int positive_sum(const int *values, size_t count) {
int sum = 0;
for(int i=0; i<count; i++) {
if(values[i]>0) sum+=values[i];
}
return sum;
}
2 C++[ | ]
C++
Copy
#include <vector>
int positive_sum (const std::vector<int> arr){
int sum = 0;
for(int i=0; i<arr.size(); i++) {
if(arr[i]>0) sum+=arr[i];
}
return sum;
}
3 Kotlin[ | ]
Kotlin
Copy
fun sum(numbers: IntArray): Int {
var res = 0
numbers.forEach {
if( it>0 ) res+=it
}
return res
}
Kotlin
Copy
fun sum(numbers: IntArray) = numbers.filter { it > 0 }.sum()
Kotlin
Copy
fun sum(numbers: IntArray) = numbers.sumBy{if(it>0) it else 0}
Kotlin
Copy
fun sum(numbers: IntArray) = numbers.sumBy { it.coerceAtLeast(0) }
Kotlin
Copy
fun sum(numbers: IntArray): Int {
var sum: Int = 0
for (n: Int in numbers) {
if(n > 0) sum += n
}
return sum
}
Kotlin
Copy
fun sum(numbers: IntArray) = numbers.fold(0) { acc, n -> if (n > 0) acc + n else acc }
4 PHP[ | ]
PHP
Copy
function positive_sum($arr) {
$sum = 0;
foreach($arr as $n) {
if( $n > 0 ) $sum += $n;
}
return $sum;
}
PHP
Copy
function positive_sum($arr) {
return array_sum(array_filter($arr, function ($v) {return $v>0;}));
}
PHP
Copy
function positive_sum($arr) {
$sum = 0;
foreach ($arr as $v) {
$sum += $v>0 ? $v : 0;
}
return $sum;
}
PHP
Copy
function positive_sum($arr) {
return array_reduce($arr, function($sum, $v){
if ($v > 0) $sum += $v;
return $sum;
}, 0);
}
편집자 Jmnote Apple Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.