Looking for 1 in the series

Source: Internet
Author: User

I. Topics and Requirements
    • 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, design ideas

The number of 2-digit and 3-digit 1 is calculated first, and then the algorithm of 1 is recursively programmed.

Third, the experimental code

#include <iostream.h>intMain () {intnum; inttag=1; intCount=0; intHeigher,cur,lower; cout<<"Please enter data:"; CIN>>num;  while(num/tag!=0) {Heigher=num/(tag*Ten); Cur= (Num/tag)%Ten; Lower=num%tag; Switch(cur) { Case 0: Count=count+heigher*tag;  Break;  Case 1: Count=count+heigher*tag+lower+1;  Break; default: Count=count+ (heigher+1)*tag;  Break; } tag=tag*Ten; } cout<<"1 The number of occurrences is:"<<count<<Endl; return 0;}

Four, the experiment:

Looking for 1 in the series

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.