标签:ios inpu 题目 turn form code sam task while
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的次数(如:11算出现两次1)
从低位到高位,计算每一位为1时的数字个数,进行累加
N/(a*10) //取指针i指向的数字左边数字
N/a%10 //取指针i指向的数字
N%a //取指针i指向的数字右边数字
#include <iostream>
using namespace std;
/*
测试点4,6超时
*/
int main(int argc,char * argv[]) {
int n,t=0,a=1,left,now,right;
scanf("%d",&n);
while(n/a>0) {
left = n/(a*10),now=n/a%10,right=n%a;
if(now==0)t+=left*a;
else if(now==1)t+=left*a+right+1;
else t+=(left+1)*a;
a*=10;
}
printf("%d",t);
return 0;
}
PAT Advanced 1049 Counting Ones (30) [数学问题-简单数学问题]
标签:ios inpu 题目 turn form code sam task while
原文地址:https://www.cnblogs.com/houzm/p/12258899.html