Number of occurrences of the Number 1 from 1 to n

Source: Internet
Author: User

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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.