C++ Program to count ordinary numbers in range 1 to n

Suppose we have a number n. A number is a positive integer n, and that said to be an ordinary number if in the decimal notation all its digits are the same. We have to count the number of ordinary numbers in range 1 to n.

Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can. This problem we can solve by some basic logics or brute-force approach. Follow the following contents to understand the approach better.

So, if the input of our problem is like n = 100, then the output will be 18, because the numbers are 1 to 9 and 11, 22, ... 99, so there are 18 total numbers.


To solve this, we will follow these steps −

s := 0
for initialize p := 1, when p <= n, update (increase s by 1), do:
   p := p / ((p mod 10) * (p mod 10 + 1))
   if p mod 10 is same as 0, then:
      (increase p by 1)
return s


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int n){
   int s = 0;
   for (int p = 1; p <= n; s++){
      p = p / (p % 10) * (p % 10 + 1);
      if (p % 10 == 0)
   return s;
int main(){
   int n = 100;
   cout << solve(n) << endl;