首页 技术 正文
技术 2022年11月6日
0 收藏 608 点赞 928 浏览 1197 个字

1049. Counting Ones (30)

时间限制100 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, Yue

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的个数和。
找规律题,计算每一位对应的1的个数,然后相加,每一位的1的计算情况分三种情况:
1.如果当前位数字为0,那么该位的1的个数由更高位的数字确定。比如2120,个位为1的个数为212 * 1 = 212(个位的单位为1)。
2.如果当前位数字为1,那么该位的1的个数不但由高位决定,还由低位数字决定。比如2120百位为1,那么百位数字1的个数为2 * 100 + 20 + 1 = 221个(百位的单位为100)。
3.如果当前位数字大于1,那么该位数字1的个数为(高位数+ 1) * 位数单位。比如2120十位为2,那么十位数字1的个数为(21 + 1) * 10 = 220个(十位的单位为10)
4.继续按照上文,2120千位为2,那么千位为1的个数为(0 + 1)*1000 = 1000
5.综上2120以内的所有数字中出现1的个数为1653个。代码
#include<iostream>
using namespace std;int CountOnes(int n)
{
int factor = 1,lownum = 0,highnum = 0,cur = 0,countones = 0;
while(n/factor)
{
highnum = n/(factor*10);
lownum = n - (n/factor)*factor;
int cur = (n/factor) % 10;
if(cur == 0)
{
countones += highnum * factor;
}
else if (cur == 1)
{
countones += highnum * factor + lownum + 1;
}
else
{
countones += ( highnum + 1) * factor;
}
factor *= 10;
}
return countones;
}int main()
{
int n;
while(cin >> n)
{
cout << CountOnes(n);
}
}

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289