상세 컨텐츠

본문 제목

[JAVA] 재귀함수(recursive function) 연습1

ALGORITHM

by charBS 2022. 1. 8. 15:32

본문

재귀함수(recursive function) 란 ?
함수를 정의할 때 자신을 다시 호출하는 함수

 

재귀 함수를 정의할 때는 재귀의 탈출 조건이 중요하다

 

 

정수 n까지 더하기
public class RecurciveTest

	static int Sum(int n) {
    	if (n==1) return 1;
        return n+Sum(n-1);
    }
    	
	public static main(String[] args) {
		int num = 5;
        System.out.println(Sum(5));
   	}
}

 

 

 

정수 n까지 곱하기
public class RecurciveTest

	static int Sum(int n) {
    	if (n==1) return 1;
        return n+Sum(n-1);
    }
    	
	public static main(String[] args) {
		int num = 5;
        System.out.println(Sum(5));
   	}
}

 

 

 

10진수를 2진수로 바꾼것을 출력하기
package practice;

import java.util.Scanner;

public class RecursiveTest {
	public static void main(String[] args) {
    
		Scanner scan = new Scanner(System.in);
		int decimal = scan.nextInt();
		decimalToBinary(decimal);
		
	}
	
	public static void decimalToBinary(int dec)
	{
		if (dec/2==1) {
			System.out.print("1");
			System.out.print(dec%2);
			return;			
		} 
		else if (dec/2==0) {
			System.out.print(dec%2);
		}
        
		decimalToBinary(dec/2);
		System.out.print(dec%2);
	}
}

 

실행결과

 

 

 

백준 17478번 - 재귀함수가 뭔가요?
// 17478

 

 

 

 

관련글 더보기