[Java알고리즘] 7-2. 이진수 출력(재귀)

🌼 Problem


🍔 Solution 1

import java.util.Scanner;

public class _72_이진수출력 {

    // 방법 1
    public static void Solution(int n){
        String answer = "";

        if(n==0){
            return;
        }else{
            Solution(n/2);
            answer += n%2;
        }
        System.out.print(answer);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();
        Solution(input);

    }
}

[결과]


🍪 강사 Solution

import java.util.Scanner;

public class _72_이진수출력 {

    // 방법 2 : 강사
    public static void Solution(int n){
        if(n==0) return;
        else{
            Solution(n/2);
            System.out.print(n%2+ " ");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();
        Solution(input);

    }
}

[결과]

좋은 웹페이지 즐겨찾기