解法一:如果n!最末尾位0,则右移一位得到商,如果末尾是1,则不能被2整除,是奇数,这个问题等同与求n!中质有质因数2的个数。。最后结果再加1

代码:

#include<iostream>
using namespace std;
int main()
{
    int n,sum;
    sum=0;
    cin>>n;
    while(n)
    {
        n>>=1;
        sum+=n;
    }
    cout<<sum+1<<endl;
    system("pause");
    return 0;
}

解法二:N减去N的二进制表示中1的数目,然后再加1。。这也是一个规律。。

代码:

#include<iostream>
using namespace std;

int getNum(int n)
{
    if(n==0) return 0;
    int count=0;
    while(n)
    {
        n&=(n-1);
        count++;
    }
    return count;
} 

int main()
{
    int n,sum;
    sum=0;
    cin>>n;
    cout<<n-getNum(n)+1<<endl;
    system("pause");
    return 0;
}

 

相关文章:

  • 2021-12-19
  • 2022-12-23
  • 2021-06-06
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2021-04-19
  • 2022-01-01
猜你喜欢
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-06-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-24
相关资源
相似解决方案