1 to N (positive integer) 1 occurrences of the number

Source: Internet
Author: User

First, the topic 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. Requirements:Write a function f (n) that returns the number of "1" that occurs 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. requires the design idea, code implementation, implementation, personal summary in the form of blog post. (due date 2015-4-30 night 18:00)second, the design ideafirst of all, when N is 1~ab (2=<a=<9), the number of 10-bit and single-digit "1" can be affirmed that the 10-bit "1" is related to the "1" on the single digit, that is, 10 "1" is b-0+1, the single-digit "1" is related to the 10-bit on-digit "1" is a-0+1, so use a count variable to remember the number of "1". third, the code
#include <iostream.h>int main () {int count=0,i,n,temp;cout<< "Please enter the value of N:"; Cin>>n;for (i=1;i<=n;i++ {temp=i;//records the value of I while (temp!=0) {count+= (temp%10==1)? 1:0;temp/=10;//directly with I, I finally became the 0,++ words became 1, the dead cycle of}}cout<< Count<<endl;return 0;}
Four,when n=101, hundreds of "1" There are 2, 10 on the "1" There are 10, single-digit "1" There are 11, a total of 23v. SummaryThis topic and previous topics have a similar, like before the reader to buy a number of books of the lowest price problem, have to find out some of the range of links or laws, design algorithms to solve the problem, in short, it is important to find the law, especially the need for skills of the programming problem, skills are very important. But remember that not all topics have skills, so specific topics specific considerations, to find the best algorithm.  

1 to N (positive integer) 1 occurrences of the number

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.