Problem:
Enter the decimal number n to count the number of occurrences of all 1 in the continuous number from 1 to n.
For example:
• N = 3, F (3) = 1 (only one digit) • (two digits) • n = 13, F (13) = 6 2 + 4 • n = 23, F (23) = 13 3 + 10 • n = 33, F (33) = 14 10 + 4 •...... • N = 99, F (99) = 20 10 + 10 • N = 123 • single digit appears 1 count: 13 • ten digits appear 1 count: 20 • hundreds appear 1 count: 24 • Likewise, we can analyze 4-digit, 5-digit...
Summary rules:Calculation method: you can calculate the number of occurrences of 1 on each bit, and then calculate the total occurrences.
Question:How to calculate the number of occurrences of 1 in a specific location? Assume that n = ABCDE is used to calculate the number of occurrences of 1 in a hundred bits. It is affected by three factors: a hundred-bit number, a hundred-bit number, and a hundred-bit number. When the number of digits C is 0, the number of occurrences of 1 on the number of digits is only affected by the number of digits over 12045: the number of occurrences of 1 in a hundred bits is 12*100 = 1200. When the number of digits c = 1 in a hundred bits, the number of occurrences of 1 in a hundred bits is only measured by a number larger than bits, the number below 12145 digits affects 100: the number of times that a hundred digits appear on one hundred digits is 12 * + 45 + 1. When a hundred digits C> 1, the number of occurrences of 1 in a hundred bits is only affected by the number of more than 12345: the number of occurrences of 1 in a hundred bits (12 + 1) x 100 = 1300 is still calculated by others.
#include <iostream>using namespace std;void fun(int N){int factor=1;int count=0;int low,cur,high;while (N/factor){low = N - (N/factor)*factor;cur = (N/factor)%10;high = N/(factor*10);switch(cur){case 0:count += high*factor;break;case 1:count += high*factor+low+1;break;default:count += (high+1)*factor;break;}factor *=10;}cout<<count<<endl;}int main(){int n;while(cin>>n){if(n==-1) break;fun(n);}}