본문 바로가기
자바(Java)/자바기초

[자바기초.023] 재귀함수 코딩 연습문제

by 긱펀 2024. 3. 20.
반응형

[자바기초.023] 재귀함수 코딩 연습문제

-링크: https://codingbat.com/java/Recursion-1

*문제의 정답은 제일 아래 "더보기" 클릭하시면 확인 가능합니다.

 

 

[문제1] 아래의 코드에서 "write code here" 부분을 코딩하여, findSum 메소드를 완성하세요. 이 메소드는 변수 n 값과 크기가 같거나 작은 양의 정수의 합을 리턴하는 재귀 메소드 입니다. 예를 들어 findSum(3)은 1+2+3 = 6, 즉 6을 리턴합니다. 아래 예제 코드는 15를 리턴해야 합니다.

(Replace the “write code here” below with the code to complete the findSum method. The method should take the sum of every value that is less than or equal to n. For example, findSum(3) should return 6. The output of the program should be 15.)

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
  public static int findSum(int n)
  {
      // write code here
     
  }
 
  public static void main(String[] args) {
     System.out.println(findSum(5)); // 15
  }
}
 
cs

 

 

[문제2]

 

 

 


 

[문제 정답은 아래의 "더보기" 클릭]

더보기

[문제1 정답]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Main {
  public static int findSum(int n)
  {
      // write code here
      if(n == 1) {
          return 1;
      }
      else {
          return n + findSum(n-1);
      }
  }
 
  public static void main(String[] args) {
     System.out.println(findSum(5)); // 15
  }
}
 
cs

 

[문제2 정답]

 

 

 

728x90
반응형

댓글