1049. Counting Ones (30) [count 1] -- PAT (Advanced Level) Practise

Source: Internet
Author: User

1049. Counting Ones (30) [count 1] -- PAT (Advanced Level) Practise
Question Information

1049. Counting Ones (30)

Time limit 10 MS
The memory limit is 65536 kB.
Code length limit: 16000 B

The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. for example, given N being 12, there are five 1's in 1, 10, 11, and 12.

Input Specification:

Each input file contains one test case which gives the positive N (<= 2 ^ 30 ).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:
12
Sample Output:
5

Solutions

In the beauty of programming, the number of numbers ranging from 0 to N containing number 1 is calculated.

AC code
#include 
  
   int get(long long n){    long long cur = 0, before = 0, after = 0, i = 1, cnt = 0;    while ((n / i) != 0){        cur = n / i % 10;        before = n / i / 10;        after = n - (n / i) * i;        if (cur == 0){            cnt += before * i;        }else if (cur == 1){            cnt += before * i + after + 1;        }else {            cnt += (before + 1) * i;        }        i *= 10;    }    return cnt;}int main(){    long long a;    scanf("%lld", &a);    printf("%d\n", get(a));    return 0;}
  

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.