C++ code to find total number of digits in special numbers


Suppose, we are given an integer number k. We call a number special number if all the digits in that number are the same. For example, 1, 11, 1111 are special numbers. We count the special numbers in order 1, 11, 111, 1111, 2, 22, 222, 2222, 3, 33, 333, 3333, and so on. We have to find out the total number of digits that are in special numbers up to k. The value of k is not greater than 10000.

So, if the input is like k = 9999, then the output will be 90.

Steps

To solve this, we will follow these steps −

s := convert k to string
Define an array v of size: := {0, 1, 3, 6, 10}
print(((s[0] - '0') - 1) * 10 + v[length of s])

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int k) {
   string s = to_string(k);
   int v[] = {0, 1, 3, 6, 10};
   cout<< ((s[0] - '0') - 1) * 10 + v[s.length()] << endl;
}
int main() {
   int k = 9999;
   solve(k);
   return 0;
}

Input

9999

Output

90

Updated on: 11-Mar-2022

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements