Find the number of 1 to n integers that appear as 1

Source: Internet
Author: User

Programming beauty 2.4

When n = 12, the numbers 1, 11, and 12 contain 1, so the number of 1 is 5.

Line 9 is used to prevent factor overflow.

 1 #include <iostream> 2 #include <stdlib.h> 3 #include <time.h> 4 using namespace std; 5  6 int countOne(int n) { 7     int ans = 0; 8     int factor = 1; 9     while (n / factor >= 10) { // avoid overflow10         int high = n / factor / 10;11         int low = n % factor;12         int current = (n / factor) % 10;13         if (current == 0) {14             ans += high * factor;15         } else if (current == 1) {16             ans += high * factor + low + 1;17         } else {18             ans += (high + 1) * factor;19         }20         factor *= 10;21     }22     if (n / factor == 1) ans += (n % factor) + 1;23     else if (n / factor != 0) ans += factor;24     return ans;25 }26 27 int bruteForce(int n) {28     int ans = 0;29     for (int i = 1; i <= n; ++i) {30         int tmp = i;31         while (tmp) {32             if (tmp % 10 == 1) ans++;33             tmp /= 10;34         }35     }36     return ans;37 }38 39 int main() {40     srand(time(NULL));41 42     for (int i = 0; i < 100; ++i) {43         int n = rand() % 9999999;44         int c1 = countOne(n);45         int c2 = bruteForce(n);46         if (c1 != c2) {47             cout << c1 << " " << c2 << " " << n << endl;48         }49     }50     return 0;51 }

 

Find the number of 1 to n integers that appear as 1

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.