【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
201 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
245 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
244 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
230 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
146 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
166 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
335 0
|
存储 定位技术 C++
【PAT甲级 - C++题解】1091 Acute Stroke
【PAT甲级 - C++题解】1091 Acute Stroke
146 0
|
12月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
10月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
394 12