在 C++ 中打印一个非常大的数字中所有 3 位重复数


在此问题中,我们给定一个数字。我们必须打印出所有 3 位重复数。

让我们举个例子来理解这个问题,

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

为了解决这个问题,我们将使用存储为字符串的大数字。数字的位数被计数为字符。现在,我们将检查前三个数字,然后从第三个索引开始到末尾获得一个新的数字。在此之后,我们将检查接下来的 3 位数字是否计数其频率。最后,打印出频率大于 1 的所有 3 位数字。

示例

以下代码将实现我们的解决方案,

 在线演示

#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);
}

输出

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

更新于:22-1 月-2020

243 次浏览

开始您的 事业

完成课程以获得认证

开始吧
广告
© . All rights reserved.