zoukankan      html  css  js  c++  java
  • 1049. Counting Ones (30)

    The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.

    Input Specification:

    Each input file contains one test case which gives the positive N (<=230).

    Output Specification:

    For each test case, print the number of 1's in one line.

    Sample Input:
    12
    
    Sample Output:
    5
    

    如果穷举的话太麻烦了,还要排着计算每个数有几个1。可以假定某一位是1,看一下此时有多少个数满足不超过n,假如32105这个数,假定十位是1,他的高位是321,低位是5,高位肯定不能是321(32110 > 32105),当高位取0-320时,低位可以取0-9,此时是(320 + 1)* 10。接洗下来假设百位是1,百位本来就是1,高位为32,低位为05,高位可以取0-32,高位取0-31时,低位可以取0-9,高位取32时,低位只可以取0-5,所以此时是32 * 100 + 5 + 1。继续假设千位是1,高位和低位都可以尽情取所在范围内的数,即高位取0-3,低位可以取0-999,结果很清楚了已经(3+1)*1000。可见只需要分所假设位是0,1,和其他的情况即可。
    代码:
    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <set>
    #include <cstring>
    using namespace std;
    
    int main()
    {
        int n;
        cin>>n;
        int base = 1;
        int low,now,high;
        int ans = 0;
        while(n/base)
        {
            high = n / (base * 10);
            now = (n / base) % 10;
            low = n % base;
            if(now == 0)//now 位 要是1 则high必然要减小1
            ans += high * base;
            else if(now == 1)//now位本来就是1 则high位不变
            ans += high * base + low + 1;
            else//那么low可以取base个
            ans += (high + 1) * base;
            base *= 10;
        }
        cout<<ans;
    }
  • 相关阅读:
    nginx 配置优化(简单)
    Nginx 安装
    Smokeping安装教程
    test [ ] 四类
    if语句中的判断条件(nginx)
    力扣 1431. 拥有最多糖果的孩子 python
    力扣 1672. 最富有客户的资产总量+1512. 好数对的数目 python
    力扣 剑指 Offer 58
    力扣 8. 字符串转换整数 (atoi)python--每日一题
    力扣 7. 整数反转python 每日一题
  • 原文地址:https://www.cnblogs.com/8023spz/p/8052534.html
Copyright © 2011-2022 走看看