Java十进制转二进制,递归算法

用递归算法求一个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);
	}
}
    原文作者:递归算法
    原文地址: https://blog.csdn.net/Sherry_Rui/article/details/51050467
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞