For example, if N = 11, the result is 4 (only 1, 10, 11 contains 1. conventional method (brute force) time complexity O (n * logn) low efficiency when n is large. [Cpp] # include <iostream> # include <cstdio> using namespace std; int function (int n) {int count = 0; for (int I = 1; I <= n; I ++) {int j = I; while (j) {if (j % 10 = 1) count ++; j/= 10 ;}} return count;} int main () {int n; while (scanf ("% d", & n )! = EOF) {printf ("% d \ n", function (n) ;}return 0 ;}2. programming Method (time complexity O (logn) [cpp] # include <iostream> # include <cstdio> using namespace std; int function (int n) // calculate the number of occurrences of 1 for each bit {int factor = 1; // the weight of this bit is int res = 0; int low, cur, high; while (n/factor) {low = n % factor; // The low level of the number cur = n/factor % 10; // Number of the current position of the number high = n/factor/10; // The highest digit of the number if (cur = 0) res + = high * factor; else if (cur = 1) res + = high * factor + low + 1; else res + = (high + 1) * factor; factor * = 10;} www.2cto.com return res ;} int main () {int n; while (scanf ("% d", & n )! = EOF) {printf ("% d \ n", function (n) ;}return 0 ;}