Count rotations divisible by 4 - GeeksforGeeks
Given a large positive number as string, count all rotations of the given number which are divisible by 4.
Read full article from Count rotations divisible by 4 - GeeksforGeeks
Given a large positive number as string, count all rotations of the given number which are divisible by 4.
For large numbers it is difficult to rotate and divide each number by 4. Therefore, ‘divisibility by 4’ property is used which says that a number is divisible by 4 if the last 2 digits of the number is divisible by 4. Here we do not actually rotate the number and check last 2 digits for divisibility, instead we count consecutive pairs (in circular way) which are 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;
}
Read full article from Count rotations divisible by 4 - GeeksforGeeks