算法:十进制转二进制

/**
 * <p>
 * 递归方法,它的返回数N的二进制表示中1的个数。 利用这样的事实,如果N是奇数,那么其1的个数等于N/2的二进制表示中1的个数加1
 * </p>
 * 
 * @author wangchao
 * @version 1.0.0
 * @since 1.0.0
 *
 */
public class Example2 {
	private String function1(int n, StringBuilder sb, int count) {
		int quotient = n / 2;// 商
		int remainder = n - 2 * quotient;// 余数
		if (remainder == 1) {
			count++;
		}
		if (quotient == 0) {
			sb.insert(0, remainder);
		} else {
			sb.insert(0, remainder);
			this.function1(quotient, sb, count);
		}
		return sb.toString();
	}

	/**
	 * <p>
	 * 十进制转二进制
	 * </p>
	 */
	public String function1(int n) {
		return this.function1(n, new StringBuilder(), 0);
	}

	public static void main(String[] args) {
		Example2 em = new Example2();
		String s = em.function1(9);
		System.err.println(s);
	}
}

  计数的方法原本是想在递归里实现的,但是发现函数在return的时候,并没有按照预想的实现。所以,要实现计数的话,应该需要再写一个for循环遍历吧。如果以后找到了return失败的原因,再来更新代码。

原文地址:https://www.cnblogs.com/wangchaoBlog/p/6077835.html