ในปัญหานี้ เราได้รับตัวเลข และเราต้องพิมพ์ตัวเลขซ้ำทั้ง 3 หลัก
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
Input: 98769876598765 Output: 987: 3 times 876: 3 times 765: 2 times
เพื่อแก้ปัญหานี้ เราจะใช้ตัวเลขจำนวนมากที่เก็บไว้เป็นสตริง ตัวเลขของตัวเลขจะถูกนับเป็นตัวอักษร ตอนนี้เราจะตรวจสอบตัวเลขสามตัวแรกแล้วเริ่มจากดัชนีที่ 3 ไปที่จุดสิ้นสุดและรับหมายเลขใหม่ หลังจากนี้เราจะตรวจสอบเลข 3 หลักถัดไป นับความถี่ สุดท้ายให้พิมพ์เลขทั้ง 3 ตัวที่มีความถี่เกิน 1 ตัว
ตัวอย่าง
โค้ดด้านล่างจะใช้โซลูชันของเรา
#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