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

时间:2021-04-12 02:10:44

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

#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);
}