PAT甲级-1049 Counting Ones (30分)

点击链接PAT甲级-AC全解汇总

题目:
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 (≤2​30​​ ).

Output Specification:
For each test case, print the number of 1’s in one line.

Sample Input:

12

Sample Output:

5

题意:
输入一个数N,算1,2,…,N,这些数中一共有多少数字1出现;

我的思路:
暴力求解会超时,只能通过数字直接计算。
经过大佬点拨,对每一位的情况来计算所有的个数。
假设a位当前的位数,1个位,10十位,100百位…以此类推

  • 不管当前位值是多少,左边多大就计算了多少次当前位为1的情况,以及当前位为1的时候,右边几位就计算了多少次,所以是左边数字乘以当前位(左边* a);
  • 如果当前位是1,那么还得再加上上面漏算的部分,就是1本身,和右边的数(右边 + 1
  • 如果当前位是大于1的,还得加上当前位是1的时候,计算了a次(a)

其中:左边=N/(a*10),当前=N/a%10,右边=N%a;

我的代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int N,a=1,ans=0;
    cin>>N;
    while(N/a)
    {
        ans+=N/(a*10)*a;
        if(N/a%10==1)ans+=N%a+1;//当前为1,多right+1次
        else if(N/a%10>1)ans+=a;//当前>1,加上当前为1时右边计算的a次
        a*=10;
    }
    cout<<ans;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值