1049 Counting Ones (30 分)(數學問題)
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的個數
分析:
這是一道數學問題。從第一位(個位)到最高位,設now為當前位的數字,left為now左邊的所有數字構成的數字,right是now右邊的所有數字構成的數字。只需要一次次累加對於當前位now來說可能出現1的個數,然後把它們累加即可。a表示當前的個位為1,十位為10,百位為100類推。
對於now,有三種情況:
1.now == 0 : 那麼 ans += left * a; //因為now==0說明now位只有在left從0left-1的時候會產生1,所以會產生left次,但是又因為右邊會重複從0999...出現a次
2.now == 1 : ans += left * a + right + 1;//now = 1的時候就要比上一步多加一個當now為1的時候右邊出現0~right個數導致的now為1的次數
3.now >= 2 : ans += (left + 1) * a;//now大於等於2就左邊0left的時候會在now位置產生1,所以會產生left次,但是又因為右邊會重複從0999...出現a次
原文連結:
柳神題解
超時題解(22分)
我的思路是:把1~n的數字轉成字串,然後判斷裡面的1,結果兩個用例超時,,,
#include <bits/stdc++.h>
using namespace std;
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif
long long int n,num,cnt=0;
scanf("%lld",&n);
for(long long int i=1; i<=n; i++)
{
string s=to_string(i);
for(int j=0;j<s.size();j++){
if(s[j]=='1')
cnt++;
}
}
printf("%lld\n",cnt);
return 0;
}
本文來自部落格園,作者:勇往直前的力量,轉載請註明原文連結:https://www.cnblogs.com/moonlight1999/p/15584791.html