计算可被 4 整除的旋转次数的 C++ 程序
给定一个大的正数作为字符串,计算给定数的所有可被 4 整除的旋转。
例子:
Input: 8
Output: 1
Input: 20
Output: 1
Rotation: 20 is divisible by 4
02 is not divisible by 4
Input : 13502
Output : 0
No rotation is divisible by 4
Input : 43292816
Output : 5
5 rotations are : 43292816, 16432928, 81643292
92816432, 32928164
对于大数字,很难将每个数字旋转并除以 4。因此,使用“被 4 整除”属性,即如果数字的最后 2 位数字可以被 4 整除,则该数字可以被 4 整除。这里我们做实际上并没有旋转数字并检查最后 2 位数字的可分性,而是我们计算可被 4 整除的连续对(以循环方式)。
插图:
Consider a number 928160
Its rotations are 928160, 092816, 609281, 160928,
816092, 281609.
Now form pairs from the original number 928160
as mentioned in the approach.
Pairs: (9,2), (2,8), (8,1), (1,6),
(6,0), (0,9)
We can observe that the 2-digit number formed by the these
pairs, i.e., 92, 28, 81, 16, 60, 09, are present in the last
2 digits of some rotation.
Thus, checking divisibility of these pairs gives the required
number of rotations.
Note: A single digit number can directly
be checked for divisibility.
下面是该方法的实现。
C++
// C++ program to count all rotation divisible
// by 4.
#include
using namespace std;
// Returns count of all rotations divisible
// by 4
int countRotations(string n)
{
int len = n.length();
// For single digit number
if (len == 1)
{
int oneDigit = n.at(0)-'0';
if (oneDigit%4 == 0)
return 1;
return 0;
}
// At-least 2 digit number (considering all
// pairs)
int twoDigit, count = 0;
for (int i=0; i<(len-1); i++)
{
twoDigit = (n.at(i)-'0')*10 + (n.at(i+1)-'0');
if (twoDigit%4 == 0)
count++;
}
// Considering the number formed by the pair of
// last digit and 1st digit
twoDigit = (n.at(len-1)-'0')*10 + (n.at(0)-'0');
if (twoDigit%4 == 0)
count++;
return count;
}
//Driver program
int main()
{
string n = "4834";
cout << "Rotations: " << countRotations(n) << endl;
return 0;
}
输出:
Rotations: 2
时间复杂度: O(n),其中 n 是输入数字的位数。
有关详细信息,请参阅有关可被 4 整除的计数旋转的完整文章!