PAT (Advanced Level) 刷题记录 1049 Counting Ones (30分)

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 (≤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 出现的个数:
我们可以算出每一位上出现1的个数,然后累加起来。
根据每一位上值的不同,可分为三种情况:
(1)值为0
(2)值为1
(3)2~9

为解决这个问题设立三个变量high,low,now。
high–高位值
low–低位值
now–当前位的值,用来判断是哪种情况
举个具体的列子:
1237056
第一种情况,
0在百位上,我们统计百位上1的个数,

#include <iostream>
using namespace std;
int N;
int main() {
    cin >> N;
    int sum = 0;
    for (int i = 1; i <= N; i *= 10) {//这里是i<=N,没有等号的话会出错
        int low = N % i;
        int temp = N / i;
        int high = temp / 10;
        int now = temp % 10;
        if (now == 0)
            sum += high * i;
        else if (now == 1)
            sum += high * i + 1 * (low + 1);
        else
            sum += (high + 1) * i;
        if (high == 0)
            break;
    }
    cout << sum;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值