Number of "1" games

Source: Internet
Author: User

First, the experimental topic

Given a positive decimal integer, write down all integers starting at 1, to N, and then count the number of 1.

Requirements:

1. Write a function f (N) and return the number of "1" between 1~n, for example: f (12) = 5;

2, in the 32-bit integer range, satisfies the condition "F (N) =n" The maximum N is how much;

Second, design ideas

Law:

There are only three cases on each of them: 0,1,2-9

The first digit is the No. 0 digit, and 10 is the 1th place .... ):

0:num/(10^ (i+1)) * (10^i)

1:num/(10^ (i+1)) * (10^i) +num% (10^i) +1;

2-9: (num/(10^ (i+1)) +1) * (10^i)

Third, the core source code

1#include <iostream.h>2#include <math.h>3 4 intSHU1 (intnum)5 { 6     intFlags1;//number of digits in Mark Count 1 (1 bits, 10 10 bits)7     intnow=0;//current number of digits8     intlow=0;//lower number of digits9     intHigh=0;//high number of digitsTen     intCount=0;  One      A      while(num/flog!=0)      -     { -now= (num/flog)%Ten;  thelow=num-(num/flog*flog);  -high=num/(flog*Ten);  -         if(num<=0)  -             return 0;  +         if(0==now)//the current number is 0 o'clock Count -         { +count+=high*flog;  A         } at         Else if(1==now)//the current number is 1 o'clock Count -         { -count+=high*flog+low+1;  -         } -         Else     -         {     incount+= (high+1)*flog;  -         } toflog=flog*Ten;//number One left shift +     } -     returncount;  the } * voidMain () $ {Panax Notoginseng     intnum; -     intmax=0; thecout<<"Please enter a value to test:"; +Cin>>num; Acout<<"The number of "1" appears:"&LT;&LT;SHU1 (num) <<Endl;  the}

Iv. Procedures:

V. Summary of the Experiment

In this experiment, the most important is to find the number of "1" game in the law, find the law, the Code program will be enlightened.

Number of "1" games

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.