组合数学 - 1的个数

 1的个数

 

 

Mean: 

 输入一个n,计算小于10^n的正整数中含有1的数的个数。

analyse:

这题是一道组合数学课后思考题。

基本思路:  组合数学乘法原则 + 容斥原理

n位数中,每位可选:{0,1,2,3,4,5,6,7,8,9},所以共有10^n种,其中要除掉每位都为0的情况,所以要减一。

其中每位上不选1的情况为:{0,2,3,4,5,6,7,8,9},所以共有9^n中,同样要除掉全部为0的情况。

Time complexity:O(n)

 

Source code:

 

//Memory   Time
// 1347K   0MS
// by : Snarl_jsb
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<climits>
#include<cmath>
#define N 1000010
#define LL long long
using namespace std;
//输入一个n,求小于10^n的正整数中有多少个1;


int main()
{
//    freopen("C:\\Users\\ASUS\\Desktop\\cin.txt","r",stdin);
//    freopen("C:\\Users\\ASUS\\Desktop\\cout.txt","w",stdout);
    int n;
    while(cin>>n)
    {
//        if(n==1)
//            puts("1");
        int sol=1;
        for(int i=1;i<=n;i++)
        {
            sol*=10;
        }
        sol--;
        int res=1;
        for(int i=1;i<=n;i++)
        {
            res*=9;
        }
        res--;
        cout<<sol-res<<endl;
    }
    return 0;
}

  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值