본문 바로가기

Algorithm/CodeUp

[CodeUp_Java] Q1258 : 1부터 n까지 합 구하기

반응형

안녕하세요! Plitche(플리체)입니다.
이번 포스팅의 주제는 Q1258 : 1부터 n까지 합 구하기 (자바, JAVA)입니다.

Intro

Question

문제 설명

정수 n이 입력으로 들어오면 1부터 n까지의 합을 구하시오.

입력

입력으로 자연수 n이 입력된다.

출력

1부터 n까지의 합을 출력한다.

예시

  • 입력 : 100
  • 출력 : 5050

Solution (풀이)

  • 풀이 1 : 메모리 11128, 시간 67
public class Answer1 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.parseInt(br.readLine());

        // 합계를 0으로 초기화 선언
        int total = 0;
        // 입력받은 숫자 만큼 for문 반복
        for (int i=1; i<=number; i++) {
            total += i;
        }
        System.out.println(total);
    }
}
  • 풀이 2 : 메모리 11148, 시간 61
public class Answer2 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.parseInt(br.readLine());

        int n = 0;    // 처음부터 시작될 숫자 n을 초기화 선언
        int total = 0;     // 합계를 0으로 초기화 선언

        // 입력받은 숫자 만큼 for문 반복
        while (n++<number) {
            total += n;
        }

        System.out.println(total);
    }
}

Ranking(순위)

반응형