(14)进制转换:10->2,10->16及优化:制表法

1.十进制转化为2进制



/*
 * 需求:十进制转化为二进制
 * 思路:1.用原数据除以2,得到的商作为下次的被除数,得到的余数放在数组中
 *       2.循环结束条件是商为0
 */
public void convert(int octal) {
	int[]arr=new int[32];
	int  count=0;//将余数放在数组哪个位置
	while(octal!=0) {
		arr[count]=octal%2;
		count++;
		octal=octal/2;
	}
	for(int i=count-1;i>=0;i--) {
		System.out.print(arr[i]);
	}
	System.out.println();
	
}

优化:


/*
 * 10->2进制优化:
 * 用StringBuffer容器,这种类型中含有可直接调用的方法su,就不用数组,再倒着循环输出了
 */
public void convert10_2_1(int octal) {
	StringBuffer sb=new StringBuffer();
	while(octal!=0) {
		sb.append(octal%2);
		octal=octal/2;
	}
	sb.reverse();
	System.out.print(sb);
	System.out.println();
	
}

二、十进制转化为十六进制


for/*
 * 需求:10进制转化为16进制
 * 思路:1.用原数据除以16,得到的商作为下次的被除数,得到的余数放在数组中
 *       2.循环结束条件是商为0
 */
public void convert10_16(int octal) {
	int[]arr=new int[32];
	int  count=0;//将余数放在数组哪个位置
	while(octal!=0) {
		arr[count]=octal%16;
		count++;
		octal=octal/16;
	}
	for(int i=count-1;i>=0;i--) {                               
		if(arr[i]>9) {
			int temp=arr[i]-10;
			char ch=(char) ('A'+temp);
			
			System.out.print(ch);	
		}
		else
			System.out.print(arr[i]);
	}
	System.out.println();
	
}

优化1:鉴于int temp=arr[i]-10;      char ch=(char) ('A'+temp);  不容易想,提供一个更简单的方法,查表法

思路:将十六进制的所有数值放在数组中,根据数组下标来找对应的十六进制数,而不必分情况

如下图所示:




代码改动部分如下:


char[] chTab= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};//有字母和数字,用char类型
	for(int i=count-1;i>=0;i--) {
		System.out.print(chTab[arr[i]]);
	}

优化2:可以倒着将数据放入,就可以正着输出数据了


/*10->16算法优化2:
 * 可以倒着将数据放入,就可以正着输出数据了
 */
public void convert10_16_2(int octal) {
	int[]arr=new int[32];
	int  count=arr.length-1;//将余数放在数组哪个位置
	while(octal!=0) {
		arr[count]=octal%16;
		count--;
		octal=octal/16;
	}
	char[] chTab= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	for(int i=count+1;i<arr.length;i++) {
		System.out.print(chTab[arr[i]]);
	}
	
	System.out.println();
	
}

总结:通过以上十进制转化为其他进制,可以抽象出方法


/*
 * 通过以上的进制转化,可以看出10进制转化为其他进制,有些共性的代码
 * 所以,可以抽象成一个方法,来完成功能
 */   形式参数sys:要转化为几进制
public void convert10_other(int octal,int sys) {
	int[]arr=new int[32];
	int  count=arr.length-1;//将余数放在数组哪个位置
	while(octal!=0) {
		arr[count]=octal%sys;
		count--;
		octal=octal/sys;
	}
	char[] chTab= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	for(int i=count+1;i<arr.length;i++) {
		System.out.print(chTab[arr[i]]);
	}
	
	System.out.println();
	
}














posted @ 2017-07-05 10:02  测试开发分享站  阅读(126)  评论(0)    收藏  举报