用递归算法求一个int的二进制字符串;
思路是:递归最简单情况(递归出口)是0和1;其余的是先调用递归算出n/2的二进制字符串,然后加上n时的位数(n % 2)。
import java.util.Scanner;
public class WriteBinary {
public static String writeBinary(int n){
String binary = "";
if(n < 0)
throw new IllegalArgumentException();
if(n <= 1){
binary = binary + String.valueOf(n);
return binary;
}
else{
binary = writeBinary(n/2);
binary = binary + String.valueOf(n % 2);
}
return binary;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Please input a num : ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
String binary = WriteBinary.writeBinary(input);
System.out.println(input + " binary String is " + binary);
}
}