N的阶乘二进制表示的最低位1的位置

《编程之美》中的一道题:

#include <iostream>
#include <string>
using std::endl;
using std::string;
using std::cout;
typedef unsigned long long ULLONG;
//给定整数N,求N!的二进制表示中最低位1的位置
template<class T>
string ToBinary(T n)
{
	if (n==0)
	{
		return string("0");
	}
	const int size=8*sizeof(n);
	string binstr(size,' ');
	for (int i=0;n;i++)
	{
		binstr.at(size-i-1)=(n&1)+'0';
		n>>=1;
	}
	if(binstr.at(0)==' ')
		binstr = binstr.substr(binstr.find_first_not_of(' '));
	return binstr;
}

ULLONG Fact(ULLONG n)
{
	ULLONG rst=1;
	while(n)
	{
		rst*=n--;
	}
	return rst;
}

int FactLowestOne1(int n)
{
	int nt=n;
	int cnt=0;
	while(n>1)
	{
		cnt++;
		n&=n-1;
	}
	return nt-cnt;
}

int FactLowestOne2(int n)
{
	int cnt=0;
	while(n)
	{
		n>>=1;
		cnt+=n;
	}
	return cnt;
}

int main()
{
	ULLONG n=12;
	ULLONG fact=Fact(n);
	cout<<n<<"!="<<fact<<endl;
	cout<<"binary form: "<<ToBinary(fact)<<endl;
	cout<<"Lowest one bit(1): "<<FactLowestOne1(n)<<endl;
	cout<<"Lowest one bit(2): "<<FactLowestOne2(n);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值