📜  计算N的旋转,奇数和偶数

📅  最后修改于: 2021-04-27 06:19:38             🧑  作者: Mango

给定数字n ,任务是计算给定数字的所有奇数和偶数旋转。
例子:

Input: n = 1234
Output: Odd = 2, Even = 2
Total rotations: 1234, 2341, 3412, 4123
Odd rotations: 2341 and 4123
Even rotations: 1234 and 3412

Input: n = 246
Output: Odd = 0, Even = 3

高效方法:对于大数,很难旋转并检查每次旋转是否为奇数。因此,在这种方法中,请检查数字中存在的奇数位和偶数位的计数。这些将是这个问题的答案。
下面是上述方法的实现:
执行:

C++
// C++ implementation of the above approach
 
#include 
using namespace std;
 
// Function to count of all rotations
// which are odd and even
void countOddRotations(int n)
{
    int odd_count = 0, even_count = 0;
    do {
        int digit = n % 10;
        if (digit % 2 == 1)
            odd_count++;
        else
            even_count++;
        n = n / 10;
    } while (n != 0);
 
    cout << "Odd = " << odd_count << endl;
    cout << "Even = " << even_count << endl;
}
 
// Driver Code
int main()
{
    int n = 1234;
    countOddRotations(n);
}


Java
// Java implementation of the above approach
 
class Solution {
 
    // Function to count of all rotations
    // which are odd and even
    static void countOddRotations(int n)
    {
        int odd_count = 0, even_count = 0;
        do {
            int digit = n % 10;
            if (digit % 2 == 1)
                odd_count++;
            else
                even_count++;
            n = n / 10;
        } while (n != 0);
 
        System.out.println("Odd = " + odd_count);
        System.out.println("Even = " + even_count);
    }
 
    public static void main(String[] args)
    {
        int n = 1234;
        countOddRotations(n);
    }
}


Python3
# Python implementation of the above approach
 
# Function to count of all rotations
# which are odd and even
def countOddRotations(n):
    odd_count = 0; even_count = 0
    while n != 0:
        digit = n % 10
        if digit % 2 == 0:
            odd_count += 1
        else:
            even_count += 1
        n = n//10
    print("Odd =", odd_count)
    print("Even =", even_count)
 
# Driver code
n = 1234
countOddRotations(n)
 
# This code is contributed by Shrikant13


C#
// CSharp implementation of the above approach
 
using System;
class Solution {
 
    // Function to count of all rotations
    // which are odd and even
    static void countOddRotations(int n)
    {
        int odd_count = 0, even_count = 0;
        do {
            int digit = n % 10;
            if (digit % 2 == 1)
                odd_count++;
            else
                even_count++;
            n = n / 10;
        } while (n != 0);
 
        Console.WriteLine("Odd = " + odd_count);
        Console.WriteLine("Even = " + even_count);
    }
 
    public static void Main()
    {
        int n = 1234;
        countOddRotations(n);
    }
}


PHP


Javascript


输出:
Odd = 2
Even = 2

时间复杂度: O(n)