내 답안
class Solution {
public int solution(int n) {
int answer = 0;
for(int i =1; i<=n; i++){
if(n%2 == 0 && i%2 ==0){
answer += i*i;
}else if(n%2 == 1 && i%2 ==1){
answer += i;
}
}
return answer;
}
}
Java
복사
다른 사람 풀이법
class Solution {
public int solution(int n) {
int answer = 0;
for(int i = n; i >= 0; i -= 2)
answer += (n % 2 == 0) ? i * i : i;
return answer;
}
}
Java
복사
import java.util.stream.IntStream;
class Solution {
public int solution(int n) {
if(n%2 == 0) {
return IntStream.rangeClosed(1,n).filter(i->i%2==0).map(i->(int) Math.pow(i,2)).sum();
}
return IntStream.rangeClosed(1,n).filter(i->i%2==1).sum();
}
}
Java
복사
class Solution {
public int solution(int n) {
if (n % 2 == 1) {
return (n + 1) * (n + 1) / 2 / 2;
} else {
return 4 * n/2 * (n/2 + 1) * (2 * n/2 + 1) / 6;
}
}
}
Java
복사
class Solution {
public int solution(int n) {
int answer = 0;
if (n % 2 == 0)
for (int i = 2; i <= n; i += 2) answer += Math.pow(i, 2);
else
for (int i = 1; i <= n; i += 2) answer += i;
return answer;
}
}
Java
복사
import java.util.stream.IntStream;
class Solution {
public int solution(int n) {
return n % 2 != 0 ? IntStream.iterate(1, i -> i <= n, i -> i + 2).sum() : (int) IntStream.iterate(2, i -> i <= n, i -> i + 2).mapToDouble(operand -> Math.pow(operand, 2)).sum();
}
}
Java
복사