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

  • برمجة سي بلس بلس
  • برمجة

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 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

الأجوبة

#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;   
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...