PAT--1049. Counting Ones
来源:互联网 发布:Cisco网络排错 编辑:程序博客网 时间:2024/06/06 02:56
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~n
这n个数,要知道数字1出现的次数,可以计算出个位、十位、百位…这些数位上1出现的次数,累加起来即可。
个位:0~9的循环,即0123456789,一次循环只有1个1
十位:0~9的循环,每个数连续出现10次, 即000000000111111111….一次循环有10个1
百位:0~9的循环,每个数连续出现100次,….一次循环有100个1
…
规律性是很显然的。
#include <bits/stdc++.h>using namespace std;int n, sum;int length(int n){ int ret = 0; while(n){ ret++; n /= 10; } return ret;}int main(){#ifndef ONLINE_JUDGEfreopen("data.in", "r", stdin);#endif cin >> n; n++; int k = 10; int len = length(n); for(int i = 1; i < len; ++i){ int a = (n / k * (k / 10)); int b = (n % k > k / 10) ? (n % k < 2 * k / 10 ? (n % k - k / 10) % (k / 10) : k / 10) : 0; //cout << "a + b: " << a + b << endl; //cout << "b: " << b << endl; sum += a + b; k *= 10; } // 处理最高位 int p = n / ((int)pow(10, len - 1)); if(p == 1) sum += n % (int)pow(10, len - 1); else sum += pow(10, len - 1); cout << sum << endl; return 0;}
阅读全文
0 0
- PAT 1049. Counting Ones
- PAT 1049. Counting Ones
- PAT--1049. Counting Ones
- 1049. Counting Ones (30)-PAT
- pat 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- 【PAT】1049. Counting Ones (30)
- PAT-A 1049. Counting Ones
- PAT.1049. Counting Ones (30)
- PAT 1049. Counting Ones (30)
- PAT A 1049. Counting Ones (30)
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- 【PAT甲级】1049. Counting Ones (30)
- 1049. Counting Ones (30) PAT甲级
- PAT甲级.1049. Counting Ones (30)
- PAT甲级练习1049. Counting Ones (30)
- 创建Maven项目引入Spring MVC
- 简单说 CSS中的mask—好好利用mask-image
- Java Jtree渲染叶子实现可以添加swing组件
- Revit二次开发——怎样使用dynamo的类
- Android Studio Live Templates使用详解,提高敲代码的速度
- PAT--1049. Counting Ones
- CodeM资格赛 Round A 最长树链
- 欢迎使用CSDN-markdown编辑器
- (error) MISCONF Redis is configured to save RDB snapshots...解决
- javaweb三大技术点之servlet
- 【R语言 数据探索】实战 Diamonds数据集探索
- 正则表达式
- 使用springboot+maven出现的问题
- 字符字节流体系