1 ~ N direct 1 appears

Source: Internet
Author: User

Refer to previous statistical ideas: count the number of times that the nth digit appears on the nth digit, 10, and, respectively.

For example, ABCDE, when calculating the number of occurrences of D-bit 1, use d as the delimiter, ABC is before, and E is after.

Considerations: (n is the length-1 of D)

When D = 0, Count = before * 10 ^ N;

When d = 1, Count = before * 10 ^ N + after;

When D> 1, Count = (before + 1) * 10 ^ N;

For example:

19x8

Count the number of times 1 on X:

1) x = 0, that is, the number of 1908 X as 1 has ~ 181x, x 0 ~ 9, 19 is before, and 8 is after

Count = 19*10 ^ 1;

2) x = 1, that is, the number of 1918 X as 1 has ~ 181x, x 0 ~ 9; in addition, 1910 ~ 1918, then 19 is before, 8 is after

In this case, Count = 19*10 ^ 1 + (8 + 1 );

3) x> 1, for example, the number of 1928 X as 1 has ~ X, 0 ~ 9, 19 is before, and 8 is after

In this case, Count = (19 + 1) * 10 ^ 1;

In particular, when X is at the leftmost end, before is 0, and after is 0 at the rightmost end.

#include <stdio.h>int Count1(int n){    int count = 0,//1出现总次数    bitCount = 0,//某位1出现次数    base = 1,//基数    before = n,after = 0,  //从最右开始,则Before = n,After = 0    bitN = 0;//第N位数    while(before)//向左移,还有数时循环    {        after = n % base;        before = n / (base * 10);        bitN = (n / base) % 10;        if(bitN > 1)        {            bitCount = (before + 1) * base;        }        else if(bitN == 0)        {            bitCount = (before) * base;        }        else        {            bitCount = (before) * base + (after + 1);        }        base *= 10;        count += bitCount;    }    return count;}int main() {   int n = 121;   printf("%d\n",Count1(n));   return 0;}

 

1 ~ N direct 1 appears

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.