给定数字N ,任务是计算给定数字的所有可被10整除的旋转。
例子:
Input: N = 10203
Output: 2
Explanation:
There are 5 rotations possible for the given number. They are: 02031, 20310, 03102, 31020, 10203
Out of these rotations, only 20310 and 31020 are divisible by 10. So 2 is the output.
Input: N = 135
Output: 0
幼稚的方法:针对此问题的幼稚的方法是形成所有可能的旋转。已知对于数量为K的数量,该数量N的可能转数为K。因此,找到所有旋转,并为每个旋转检查数字是否可被10整除。这种方法的时间复杂度是二次的。
高效方法:高效方法背后的概念是,为了检查一个数字是否可以被10整除,我们只需检查最后一个数字是否为0。因此,其思想是简单地遍历给定的数字并找到计数为0。如果0的计数为F ,那么很明显,在给定数N的末尾, K旋转中的F个旋转将为0。
下面是上述方法的实现:
C++
// C++ implementation to find the
// count of rotations which are
// divisible by 10
#include
using namespace std;
// Function to return the count of
// all the rotations which are
// divisible by 10.
int countRotation(int n)
{
int count = 0;
// Loop to iterate through the
// number
do {
int digit = n % 10;
// If the last digit is 0,
// then increment the count
if (digit == 0)
count++;
n = n / 10;
} while (n != 0);
return count;
}
// Driver code
int main()
{
int n = 10203;
cout << countRotation(n);
}
C#
// CSharp implementation to find the
// count of rotations which are
// divisible by 10
using System;
class Solution {
// Function to return the count
// of all rotations which are
// divisible by 10.
static int countRotation(int n)
{
int count = 0;
// Loop to iterate through the
// number
do {
int digit = n % 10;
// If the last digit is 0,
// then increment the count
if (digit % 2 == 0)
count++;
n = n / 10;
} while (n != 0);
return count;
}
// Driver code
public static void Main()
{
int n = 10203;
Console.Write(countRotation(n));
}
}
Java
// Java implementation to find the
// count of rotations which are
// divisible by 10
class GFG {
// Function to return the count
// of all rotations which are
// divisible by 10.
static int countRotation(int n)
{
int count = 0;
// Loop to iterate through the
// number
do {
int digit = n % 10;
// If the last digit is 0,
// then increment the count
if (digit == 0)
count++;
n = n / 10;
} while (n != 0);
return count;
}
// Driver code
public static void main(String[] args)
{
int n = 10203;
System.out.println(countRotation(n));
}
}
Python
# Python3 implementation to find the
# count of rotations which are
# divisible by 10
# Function to return the count of
# all rotations which are divisible
# by 10.
def countRotation(n):
count = 0;
# Loop to iterate through the
# number
while n > 0:
digit = n % 10
# If the last digit is 0,
# then increment the count
if(digit % 2 == 0):
count = count + 1
n = int(n / 10)
return count;
# Driver code
if __name__ == "__main__" :
n = 10203;
print(countRotation(n));
Javascript
输出:
2
时间复杂度: O(N) ,其中N是数字的长度。