1049 Counting Ones(数学题)
本题为数学问题,遍历数字的各个位置根据下列公式:
将数字分为left、now、right三个位置(a表示now的位置)
1.当now=0时,now位置出现1的次数就取决于left,ans+=lefta;
2.当now=1时,now位置出现1的次数比情况1多0~right次,ans+=lefta+right+1;
3.当now>1时,now位置出现1的次数相当于left+1的情况,因为1已经出现过了,ans+=(left+1)*a;
#include <iostream>
#include<algorithm>
using namespace std;
int M, N;
int main()
{
cin >> N;
int left = 0, right = 0,now=1, a = 1, ans = 0;
while (N / a)
{
left = N / (a * 10), right = N % a;
now = N / a % 10;
if (now == 0)ans += left * a;
if (now == 1)ans += left * a + right + 1;
if (now > 1)ans += (left + 1) * a;
a *= 10;
}
cout << ans;
return 0;
}