【PAT甲级 - C++题解】1049 Counting Ones

简介: 【PAT甲级 - C++题解】1049 Counting Ones

1049 Counting Ones

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


题意

给定一个数字 N ,请你计算 1∼N 中一共出现了多少个数字 1

例如,N=12 时,一共出现了 5 个数字 1 ,分别出现在 1,10,11,12 中。


思路

具体思路在剑指offer中有详细讲解,传送门放在这里啦:

剑指offer 44. 从1到n整数中1出现的次数

代码

#include<bits/stdc++.h>
using namespace std;
int cal(int n)
{
    //将数字中每一位存入数组中
    vector<int> nums;
    while (n)    nums.push_back(n % 10), n /= 10;
    //从最高位往最低位遍历
    int res = 0;
    for (int i = nums.size() - 1; i >= 0; i--)
    {
        int left = 0, right = 0, power = 1;
        //获取当前位置左边的数字
        for (int j = nums.size(); j > i; j--)  left = left * 10 + nums[j];
        //获取当前位置右边的数字以及当前所在位数
        for (int j = i - 1; j >= 0; j--)
        {
            right = right * 10 + nums[j];
            power *= 10;
        }
        //根据当前位置的数字计算答案
        if (nums[i] == 0)  res += left * power;
        else if (nums[i] == 1) res += left * power + right + 1;
        else    res += (left + 1) * power;
    }
    return res;
}
int main()
{
    int n;
    cin >> n;
    cout << cal(n) << endl;
    return 0;
}


目录
相关文章
|
C++
【PAT甲级 - C++题解】1040 Longest Symmetric String
【PAT甲级 - C++题解】1040 Longest Symmetric String
187 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
229 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
226 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
217 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
130 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
152 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
306 0
|
存储 定位技术 C++
【PAT甲级 - C++题解】1091 Acute Stroke
【PAT甲级 - C++题解】1091 Acute Stroke
138 0
|
10月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
6月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
175 0