내 풀이
class Solution {
public int solution(int n) {
int count = 1;
int num = 0;
if(n%2 == 1){
while(count<=n){
if(count%2 == 1){
num += count;
}
count++;
}
return num;
}else{
while(count<=n){
if(count%2 == 0){
num += (count)*(count);
}
count ++;
}
return num;
}
}
}
문제점
반복문마다 조건을 확인함
다른사람 풀이 1
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;
}
}
문제점
짝수일때와 홀수일때를 -2라는 조건을 주어서 해결했고 삼항연산자를 사용하여 코드는 짧지만 반복문과 그 반복문마다 조건확인
다른사람 풀이 2
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;
}
}
}