求十进制转二进制的递归算法

eviljordan 2012-11-13 07:07:33
顺便求解释一下递归的原理
谢了!
还要求负数的~
样例输入
2
0
-12
1

样例输出
2-->10
0-->0
-12-->-1100
1-->1
...全文
514 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
javamy030 2013-01-08
  • 打赏
  • 举报
回复
好帖子啊,学习啦!!
eviljordan 2012-11-14
  • 打赏
  • 举报
回复
引用 2 楼 trocp 的回复:
不过这个不是递归,递归要尽可能少用
递归为什么要少用的?
Jordan37 2012-11-14
  • 打赏
  • 举报
回复
程序调用自身的编程技巧称为递归。
oO临时工Oo 2012-11-14
  • 打赏
  • 举报
回复
不过这个不是递归,递归要尽可能少用
oO临时工Oo 2012-11-14
  • 打赏
  • 举报
回复
	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;
	}
Jordan37 2012-11-14
  • 打赏
  • 举报
回复
结果如下: Please enter the number of decimal:-23 The binary is:-10111
Jordan37 2012-11-14
  • 打赏
  • 举报
回复
用递归解决问题的程序如下:

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);
		}
	}
}
龙四 2012-11-14
  • 打赏
  • 举报
回复
引用 4 楼 eviljordan 的回复:
引用 2 楼 trocp 的回复:不过这个不是递归,递归要尽可能少用 递归为什么要少用的?
递归的深度无法控制,太深就是StackOverflow错误

58,452

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧