Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Count the total number of digit 1 appearing in all positive integers less than or equal to a given integer n

C++ Math: Exercise-10 with Solution

Write a C++ program to count the total number of digit 1 appearing in all positive integers less than or equal to a given integer n.

Input n = 12,
Return 5, because digit 1 occurred 5 times in the following numbers: 1, 10, 11, 12.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

int count_DigitOne(int num) {
        int m = 0, k = 0, result = 0, base = 1;
        while (num > 0) {
            k = num % 10;
            num = num / 10;

            if (k > 1) { result += (num+1)*base; }
            else if (k < 1) { result += num*base; }
            else { result += num*base+m+1; }

            m += k*base;
            base *= 10;
        }
        return result;
    }

int main(void)
{
    int n = 6;
    cout << "\nTotal number of digit 1 appearing in " << n << " (less than or equal) is " << count_DigitOne(n) << endl; 
    n = 15;
    cout << "\nTotal number of digit 1 appearing in " << n << " (less than or equal) is " << count_DigitOne(n) << endl;
    n = 100;
    cout << "\nTotal number of digit 1 appearing in " << n << " (less than or equal) is " << count_DigitOne(n) << endl;
    return 0;   
}

Sample Output:

Total number of digit 1 appearing in 6 (less than or equal) is 1

Total number of digit 1 appearing in 15 (less than or equal) is 8

Total number of digit 1 appearing in 100 (less than or equal) is 21

Flowchart:

Flowchart: Count the total number of digit 1 appearing in all positive integers less than or equal to a given integer n.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to find the number of trailing zeroes in a given factorial.
Next: Write a C++ programming to add repeatedly all digits of a given non-negative number until the result has only one digit.

What is the difficulty level of this exercise?