十进制转二进制问题“栈”剖析

大家应该都做过这么一个问题吧,将任意的十进制数转换成相应的二进制或者八进制或者十六进制,这个问题不难,可以用多种方法解决,今天,笔者就三种解法剖析方法其中对栈思想的应用。

先贴出代码: 1.递归操作

 

/*the function of common manipulation */void int_to_binary1(unsigned int num){int temp;temp = num%2; /*the first number shoud be printed at the last,because this function is a recursion*/if (0 != num/2)int_to_binary1(num/2);putchar (‘0’+temp); /*print the date*/} 

 

2.位操作
/*the function of bit manipulation */
void int_to_binary2(unsigned int num)

{
	char str[17];					/*str[16] store the '/0'*/
	int i = 16-1;					/*the limit length of the binary number*/

	while (-1 != i)
	{
		str[i] = (num & 01) + '0';
		num >>= 1;
		i--;
	}
	str[16] = '/0';
	puts(str);

}
3.栈操作
/*the function of stack manipulation*/
void int_to_binary3(unsigned int num)

{
	char temp;
	SeqStack binary;

	InitStack (&binary);
	while (num >=1)
	{
		Push_Stack(&binary,(num%2)+'0');
		num /= 2;
	}

	while (!Is_Empty(&binary))
	{
		Pop_Stack (&binary,&temp);
		putchar(temp);
	}
	putchar(10);

}
分析上述三种方法:
第三种方法:
栈操作是直接应用栈的技术进行操作,很容易看出来;
 
第一种方法:
 利用的是递归函数,大家都知道,递归函数在进行递归的时候都必须有一个递归出口,否则就不能正常退出程序,当函数进行第一次递归的时候,由于没有到达出口条件,所以保留本层参数和结果,将其push(也就是所说的函数调用栈)就这样,一层一层的push,知直到到达出口条件,此时函数调用栈进行POP,也叫退层。利用这个原理,将二进制零幺代码逆序输出,这样就达到了预期的目的.
第二种方法:
	这种方法,虽说没有利用栈,但是此方法的效率和直观性是显而易见的,直接进行的位操作,也就是在内存中直接就是对零幺的翻译,在加上移位操作,更加灵活,此法是我最喜欢用的,简介直观。
就到这儿了,该去吃饭了。大家共同学习,共同进步,那里有不正确和不理解的,多多指点和留言探讨,谢谢合作。
今天又遇到一个函数,可以实现转换
_itoa(57,buffer,16); 第一个参数是要转换的数,第二个是地址,第三个是进制数


 

    原文作者:进制转换
    原文地址: https://blog.csdn.net/enyblock/article/details/6533715
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞