当前位置: 代码迷 >> Eclipse >> 求十进制转二进制的递归算法,该怎么处理
  详细解决方案

求十进制转二进制的递归算法,该怎么处理

热度:8   发布时间:2016-04-23 02:03:47.0
求十进制转二进制的递归算法
顺便求解释一下递归的原理
谢了!
还要求负数的~
样例输入
2
0
-12
1

样例输出
2-->10
0-->0
-12-->-1100
1-->1

------最佳解决方案--------------------
结果如下:

Please enter the number of decimal:-23
The binary is:-10111
------其他解决方案--------------------
	public String test1(int number){
StringBuffer bf = new StringBuffer(Integer.SIZE);
int m = 0x40000000;
bf.append(number < 0 ? 1 : 0);//符号标记

for(int i = 1; i < Integer.SIZE; i ++){
if(i > 0 && i % 4 == 0){
bf.append(" ");
}
bf.append( ( number & m ) == 0 ? 0 : 1);
m = m >> 1;
}
String str = bf.toString();
System.out.println(number + "\t \t: \t" + str);
return str;
}

------其他解决方案--------------------
不过这个不是递归,递归要尽可能少用
------其他解决方案--------------------
程序调用自身的编程技巧称为递归。
------其他解决方案--------------------
引用:
不过这个不是递归,递归要尽可能少用

递归为什么要少用的?
------其他解决方案--------------------
引用:
引用:不过这个不是递归,递归要尽可能少用
递归为什么要少用的?


递归的深度无法控制,太深就是StackOverflow错误
------其他解决方案--------------------
用递归解决问题的程序如下:


import java.util.Scanner;

public class Test1 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
Test1 t = new Test1();
int j = 1;
System.out.print("Please enter the number of decimal:");
int m = read.nextInt();
int flag = 0;
if(m < 0){
flag = 1;
}
int n = Math.abs(m);
int[] x = new int[n+2];
t.dec2bin(n,j,x);
System.out.print("The binary is:");
if (flag == 1) {
System.out.print("-");
}
for (int i = x[0]; i >= 1; i--) {
System.out.print(x[i]);
}
}

private  int[] dec2bin(int n,int i,int [] m) {
if (n < 2) {
m[i] = n;
m[0] = i;
return m;
} else {
m[i] = n % 2;
i++;
return dec2bin(n / 2,i,m);
}
}
}
  相关解决方案