เราได้รับตัวเลขขนาดใหญ่ เป้าหมายคือการนับจำนวนการหมุนเวียน (rotations) ของตัวเลขที่หารด้วย 4 ลงตัว
ใช้คุณสมบัติการหารด้วย 4: ถ้าตัวเลข 2 หลักสุดท้ายหารด้วย 4 ลงตัว ตัวเลขนั้นจะหารด้วย 4 ลงตัว
ตัวอย่าง
อินพุต: num = 15324
เอาต์พุต: 2
คำอธิบาย: การหมุนเวียน: 15324, 41532, 24153, 32415, 53241 มี 15324 และ 41532 หารด้วย 4 ลงตัว
อินพุต: num = 848484
เอาต์พุต: 6
คำอธิบาย: ทุกการหมุนเวียนหารด้วย 4 ลงตัวทั้งหมด
แนวทางการแก้ปัญหา
- แปลงตัวเลขเป็นสตริง
- วนลูปตรวจสอบแต่ละคู่ 2 ตัวเลขติดกัน
- แปลงเป็นจำนวนเต็มและตรวจสอบการหารด้วย 4
- ตรวจสอบคู่ที่ต่อท้าย-หัว (wrap-around)
การนำไปใช้ (Implementation)
#include <bits/stdc++.h>
using namespace std;
int Rotation_4(long long num) {
string str = to_string(num);
int length = str.length();
int digit = 0, count = 0;
if (length == 1) {
digit = str[0] - '0';
return (digit % 4 == 0) ? 1 : 0;
}
for (int i = 0; i < (length - 1); i++) {
digit = (str[i] - '0') * 10 + (str[i+1] - '0');
if (digit % 4 == 0) count++;
}
// ตรวจสอบคู่ต่อท้าย-หัว
digit = (str[length-1] - '0') * 10 + (str[0] - '0');
if (digit % 4 == 0) count++;
return count;
}
int main() {
long long num = 24040;
cout << "Count of rotations divisible by 4 are: " << Rotation_4(num);
return 0;
}
เอาต์พุต
Count of rotations divisible by 4 are: 4