简体   繁体   中英

How to implement a recursive method for converting an integer to binary representation

I am writing a method to recursively convert an integer value to its binary representation.

The code that I wrote below accomplishes the task by just using a method, but I'd like to know how to actually write out a full method.

import java.util.Scanner;

public class Exercise18_21 {

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal integer: ");
        int decimal    = input.nextInt();
        System.out.print("Enter a character: ");

        System.out.printf("%d decimal is binary %s",decimal,dec2Bin(decimal));
    }

    //input: integer
    //output: binary representation of integer as a string
    public static String dec2Bin(int decimal){
        return Integer.toBinaryString(decimal);
    }

}

My question is how can this be accomplished with recursion?

I want to preserve your code as mush as I can. Therefore I just add a new method successiveDivision(int)

import java.util.Scanner;

public class Exercise18_21 {

    public static void main(String args[]) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal integer: ");
        int decimal = input.nextInt();
        System.out.print("Enter a character: ");

        System.out.printf("%d decimal is binary %s", decimal, dec2Bin(decimal));

    }

    // input: integer
    // output: binary representation of integer as a string
    public static String dec2Bin(int decimal) {
        return successiveDivision(decimal);
    }

    public static String successiveDivision(int dec) {
        if (dec <= 0) {
            return "";
        } else {
            int bit = dec % 2;
            return successiveDivision(dec / 2) + bit;
        }
    }

}

You can implement it the same way you can do it with pen and paper. Use the modulo operation. divided by 2 is your parameter for the recursive call and mod 2 is your current digit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM