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