📌  相关文章
📜  计算可被 8 整除的旋转次数的 C++ 程序

📅  最后修改于: 2022-05-13 01:54:42.800000             🧑  作者: Mango

计算可被 8 整除的旋转次数的 C++ 程序

给定一个大的正数作为字符串,计算给定数的所有可被 8 整除的旋转。

例子:

Input: 8
Output: 1

Input: 40
Output: 1
Rotation: 40 is divisible by 8
          04 is not divisible by 8

Input : 13502
Output : 0
No rotation is divisible by 8

Input : 43262488612
Output : 4

方法:对于大数字,很难将每个数字旋转并除以 8。因此,使用“被 8 整除”属性,即如果数字的最后 3 位数字可以被 8 整除,则该数字可以被 8 整除。这里我们实际上并没有旋转数字并检查最后 8 位数字的可分性,而是计算可被 8 整除的 3 位数字的连续序列(以循环方式)。

插图:

Consider a number 928160
Its rotations are 928160, 092816, 609281, 
160928, 816092, 281609.
Now form consecutive sequence of 3-digits from 
the original number 928160 as mentioned in the 
approach. 
3-digit: (9, 2, 8), (2, 8, 1), (8, 1, 6), 
(1, 6, 0),(6, 0, 9), (0, 9, 2)
We can observe that the 3-digit number formed by 
the these sets, i.e., 928, 281, 816, 160, 609, 092, 
are present in the last 3 digits of some rotation.
Thus, checking divisibility of these 3-digit numbers
gives the required number of rotations. 
C++
// C++ program to count all rotations divisible
// by 8
#include 
using namespace std;
  
// function to count of all rotations divisible
// by 8
int countRotationsDivBy8(string n)
{
    int len = n.length();
    int count = 0;
  
    // For single digit number
    if (len == 1) {
        int oneDigit = n[0] - '0';
        if (oneDigit % 8 == 0)
            return 1;
        return 0;
    }
  
    // For two-digit numbers (considering all
    // pairs)
    if (len == 2) {
  
        // first pair
        int first = (n[0] - '0') * 10 + (n[1] - '0');
  
        // second pair
        int second = (n[1] - '0') * 10 + (n[0] - '0');
  
        if (first % 8 == 0)
            count++;
        if (second % 8 == 0)
            count++;
        return count;
    }
  
    // considering all three-digit sequences
    int threeDigit;
    for (int i = 0; i < (len - 2); i++) {
        threeDigit = (n[i] - '0') * 100 + 
                     (n[i + 1] - '0') * 10 + 
                     (n[i + 2] - '0');
        if (threeDigit % 8 == 0)
            count++;
    }
  
    // Considering the number formed by the 
    // last digit and the first two digits
    threeDigit = (n[len - 1] - '0') * 100 + 
                 (n[0] - '0') * 10 + 
                 (n[1] - '0');
  
    if (threeDigit % 8 == 0)
        count++;
  
    // Considering the number formed by the last 
    // two digits and the first digit
    threeDigit = (n[len - 2] - '0') * 100 +
                 (n[len - 1] - '0') * 10 + 
                 (n[0] - '0');
    if (threeDigit % 8 == 0)
        count++;
  
    // required count of rotations
    return count;
}
  
// Driver program to test above
int main()
{
    string n = "43262488612";
    cout << "Rotations: "
         << countRotationsDivBy8(n);
    return 0;
}


输出:

Rotations: 4

时间复杂度: O(n),其中n是输入数字的位数。

有关详细信息,请参阅有关可被 8 整除的计数旋转的完整文章!