2的4000次幂;

最近在看《数据结构与算法分析——C语言描述》 Mark Allen Weiss著, 冯舜玺 译。

第三章习题3.9: 计算在2的4000次幂中数字0到9的分布;

由于前面的习题都是有关链表的内容,所以看到作者把这样一道题放在这样的位置,很难不理解作者的意图了。

下面是我用链表实现的。

代码主要的内容就是: 

1、遍历链表,把所有数都乘以2;

2、遍历链表,处理所有的大于9的数,下一个节点的value加1,即相当于向高位进1,同时本节点的value减去10;

下面是代码:


node *twos_power( int power )
{
	int			i;
	node		*poly;
	node		*head;

	poly = ( node * )malloc( sizeof ( node ) );
	if( poly == NULL ){
		perror( "malloc:" );
		exit( -1 );
	}

	/* poly->coef 表示个位,十位, 百位...*/
	poly->coef = 1;
	poly->value = 2;
	poly->next = NULL;
	head = poly;
	for( i = 1; i < power; i++ ){
		poly = head;
		/*先将目前链表中的所有数都乘以2,*/
		while( poly != NULL ){
			poly->value *= 2;
			poly = poly->next;
		}
		/*再将各个位中大于10的数向上进位 */
		poly = head;
		while( poly != NULL ){
			int		multi_value;
			multi_value = poly->value;
			if( multi_value > 9 ){
				if( poly->next == NULL ){
					node	*temp;
					temp = ( node * )malloc( sizeof( node ) );
					assert( temp != NULL );
					temp->value = 1;
					temp->coef = poly->coef + 1;
					temp->next = NULL;
					poly->next = temp;
				}
				else
					poly->next->value += 1;

				poly->value -= 10;
			}
			
			poly = poly->next;
		}

	}
	return head;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值