Algorithm/CodeUp
[CodeUp_Java] Q1853 : 재귀로 1부터 n까지 합 리턴하기
Plitche
2022. 12. 5. 11:24
반응형
안녕하세요! Plitche(플리체)입니다.
이번 포스팅의 주제는 Q1853 : [기초-재귀함수] 재귀로 1부터 n까지 합 리턴하기 (자바, JAVA)입니다.
Intro
Question
문제 설명
입력
int 형 정수(n) 1개가 입력된다.
(1 <= n <= 100)
출력
1 부터 n 까지의 정수 합을 출력한다.
예시
- 입력 : 10
- 출력 : 1 2 3 4 5
Solution (풀이)
- 풀이 : 메모리 11196, 시간 : 69
public class Answer1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
// 시작, 종료, 합계
loop(1, count, 0);
}
public static void loop(int start, int end, int total) {
if (start>end) {
System.out.println(total); // 시작이 종료보다 더 작으면 출력
} else {
loop(start+1, end, total+start); // 시작을 +1 해주어 재귀함수 호출
}
}
}
Ranking(순위)
반응형