Print all 3 digit repeating numbers in a very large number in C++


In this problem, we are given a number. And we have to print all 3 digit repeating numbers.

Let’s take an example to understand the problem,

Input: 98769876598765
Output:
   987: 3 times
   876: 3 times
   765: 2 times

To solve this problem, we will use the large number which is stored string. The digits of the numbers are counted as characters. Now, we will check the first three numbers and then start from the 3rd index to the end and get a new number. After this, we will check for the next 3 digit numbers are count its frequency. In the end, print all 3 digit numbers that have frequency more than 1.

Example

The below code will implement our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printRepeatingNumber(string s) {
   int i = 0, j = 0, val = 0;
   map <int, int> threeDigitNumber;
   val = (s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0');
   threeDigitNumber[val] = 1;
   for (i = 3; i < s.length(); i++) {
      val = (val % 100) * 10 + s[i] - '0';
      if (threeDigitNumber.find(val) != threeDigitNumber.end()) {
         threeDigitNumber[val] = threeDigitNumber[val] + 1;
      } else {
         threeDigitNumber[val] = 1;
      }
   }
   for (auto number : threeDigitNumber) {
      int key = number.first;
      int value = number.second;
      if (value > 1)
         cout<<key<<": "<<value<<" times\n";
   }
}
int main() {
   string num = "98769876598765";
   cout<<"All 3 digit repreating numbers are :\n";
   printRepeatingNumber(num);
}

Output

All 3 digit repeating numbers are −
765: 2 times
876: 3 times
987: 3 times

Updated on: 22-Jan-2020

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements