본문 바로가기

코딩테스트 예제

짝수는 싫어요

class Solution {
    public int[] solution(int n) {
        int[] answer =new int[(n+1)/2];
        
        for(int i=1; i<=n; i++){   
            if(i % 2 == 1){        
                 answer[i/2] = i;
            }
        }
            return answer;
        }    
    }

코드리뷰

class Solution {
    public int[] solution(int n) {
        int[] answer =new int[(n+1)/2];		//배열의크기 int[] 배열명 = new int[1,1,2,2,3,3......50,50]
        
        for(int i=1; i<=n; i++){   			//i로 조건 걸어주기위해반복문 돌림 i가 1부터 100까지 반복{
            if(i % 2 == 1){        				//만약 1부터 100까지 반복하면서 나머지값이 1인경우 ==홀수 인경우 1, 3, 5, 7 ,9, 11, 13
                 answer[i/2] = i;				//배열명[1~100까지 반복해서 / 2(몫) ] =i;		answer[0],answer[1],answer[1]
            }
        }
            return answer;
        }    
    }