Data Structure -- algorithm (016) (input integer n, calculate the number of times 1 appears in the decimal representation of the n integers from 1 to n and)

Source: Internet
Author: User

[Statement: This article is only intended for self-Summary and mutual communication, and may be omitted. Email: Mr_chenping@163.com]

Question:

Enter an integer n to calculate the number of times 1 appears and

Question Analysis:

I. In fact, the problem can be converted to the number of occurrences of 1 in a number, which involves basic remainder and Division operations.

Algorithm Implementation:

# Include

 
  
/*** Calculate the number of digits @ digit contained in the integer @ m */int count_digit_num (int m, int digit) {int count = 0; while (m) {if (m % 10 = digit) count ++; m = m/10;} return count;} int count_digit_one (int m) {int I = 0; int count = 0; for (; I <= m; I ++) {count + = count_digit_num (I, 1) ;}return count ;} int main (int argc, char * argv []) {int m = atoi (argv [1]); printf ("% d -----> % d \ n", m, count_digit_one (m ));}

 



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.