Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนการหมุนเวียนของตัวเลขที่หารด้วย 8 ลงตัวใน C++

เราได้รับตัวเลขขนาดใหญ่ เป้าหมายคือการนับจำนวนการหมุนเวียน (rotations) ของตัวเลขที่หารด้วย 8 ลงตัว

เนื่องจากไม่สามารถหมุนเวียนตัวเลขซ้ำๆ ได้ เราจะใช้คุณสมบัติการหารด้วย 8: ถ้าตัวเลข 3 หลักสุดท้ายหารด้วย 8 ลงตัว ตัวเลขนั้นจะหารด้วย 8 ลงตัว

ตัวอย่าง

อินพุต: num = 15320

เอาต์พุต: 1

คำอธิบาย: การหมุนเวียน: 15320, 01532, 20153, 32015, 53201 มีเพียง 15320 ที่หารด้วย 8 ลงตัว

อินพุต: num = 848484

เอาต์พุต: 3

คำอธิบาย: การหมุนเวียน: 848484, 484848, 848484, 484848, 848484, 484848 ทุก 484848 หารด้วย 8 ลงตัว

แนวทางการแก้ปัญหา

  1. แปลงตัวเลขเป็นสตริง
  2. วนลูปตรวจสอบแต่ละกลุ่ม 3 ตัวเลขติดกัน
  3. แปลง 3 ตัวเลขเป็นจำนวนเต็มและตรวจสอบการหารด้วย 8
  4. ตรวจสอบกรณีพิเศษ: ตัวเลข 1 หลัก, 2 หลัก, และการต่อท้าย-หัว

การนำไปใช้ (Implementation)

#include <bits/stdc++.h>
using namespace std;

int Rotation_8(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 % 8 == 0) ? 1 : 0;
    }
    else if (length == 2) {
        int part_1 = (str[0] - '0') * 10 + (str[1] - '0');
        int part_2 = (str[1] - '0') * 10 + (str[0] - '0');
        if (part_1 % 8 == 0) count++;
        if (part_2 % 8 == 0) count++;
        return count;
    }
    else {
        for (int i = 0; i < (length - 2); i++) {
            digit = (str[i] - '0') * 100 + (str[i+1] - '0') * 10 + (str[i+2] - '0');
            if (digit % 8 == 0) count++;
        }
    }
    
    // ตรวจสอบการต่อท้าย-หัว (wrap-around)
    digit = (str[length-1] - '0') * 100 + (str[0] - '0') * 10 + (str[1] - '0');
    if (digit % 8 == 0) count++;
    
    digit = (str[length-2] - '0') * 100 + (str[length-1] - '0') * 10 + (str[0] - '0');
    if (digit % 8 == 0) count++;
    
    return count;
}

int main() {
    long long num = 24040;
    cout << "Count of rotations divisible by 8 are: " << Rotation_8(num);
    return 0;
}

เอาต์พุต

Count of rotations divisible by 8 are: 3