Find out the number of 1 in 1-n

Source: Internet
Author: User

First, the topic

Given a positive integer in decimal, write down all integers starting with 1, to N, and then count the number of "1" that appears. Requirement: Write a function f (n) to return the number of "1" occurrences between 1 and N. For example F (12) = 5. Within a 32-bit integer range, the maximum n of the "F (n) =n" that satisfies the condition is what. Second, the concept of design can be realized at the beginning of the idea is to traverse each number to 10 to see if it equals to the statistics, but the time complexity is high, not the optimal algorithm. Another better algorithm is to analyze the number of 1 occurrences of a positive integer n, that is, its single-digit, 10-bit, hundred ... The number of the 1. First, look for the law: F (=2+4=6f) =3+10=13f (93) =4+10=14f =10+10=20 ... But the formula is not calculated and cannot be achieved. The algorithm of ergodic type is given. Third, the Code
1#include <iostream.h>2 3 intMain ()4 {5     intCount=0, i,n,temp;6cout<<"Please enter the number n,n=";7Cin>>N;8      for(i=1; i<=n;i++)9     {Tentemp=i; One          while(temp!=0) A         { -count+= (temp%Ten==1)?1:0; -Temp/=Ten; the         } -     } -cout<<"F ("<<N<<")="<<count<<Endl; -     return 0; +}

Iv. Results of operation

V. Summary

The problem is still the optimal code, but the better algorithm will not be implemented, in the search for the optimal algorithm needs to be improved.

Find out the number of 1 in 1-n

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.