• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    해결됨

어떤 부분이 오답인지 궁금합니다

23.06.28 11:44 작성 조회수 173

0

import java.io.*;

public class Main {
    public int solution(int n) {
        int answer = 0, sum = 0, lt = 0;

        for (int rt = 0; rt <= n/2+1; rt++) {
            sum += rt;
            if (sum == n) answer++;

            while (sum >= n) {
                sum -= lt++;
                if (sum == n) answer++;
            }
        }

        return answer;
    }

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        System.out.print(main.solution(n));
    }
}

 

따로, n/2+1 크기만큼의 배열을 생성해주지 않는 풀이인데, 어느 부분이 잘못되서 오답처리가 되는 것인지 잘 모르겠습니다.

답변 1

답변을 작성해보세요.

1

안녕하세요^^

아래 코드를 실행시켜 보세요. n = 15을 입력하고 실행시켜 출력되는 값을 보면 알 수 있을 겁니다. 참고로 출력되는 sum값은 lt부터 rt까지의 합을 의미합니다. 그리고 sum은 자연수의 합이라고 문제에 나와 있습니다.

import java.io.*;

public class Main {
    public int solution(int n) {
        int answer = 0, sum = 0, lt = 0;

        for (int rt = 0; rt <= n/2+1; rt++) {
            sum += rt;
            if (sum == n){
		answer++;
		System.out.println(lt + " " + rt + " "+ sum);
	    }

            while (sum >= n) {
                sum -= lt++;
                if (sum == n){
			answer++;
			System.out.println(lt + " " + rt + " "+ sum);
		}

            }
        }

        return answer;
    }

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        System.out.print(main.solution(n));
    }
}
재영님의 프로필

재영

질문자

2023.06.29

감사합니다!