Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count rotations of N which are Odd and Even in C++
We are given a number N. The goal is to count the rotations of N that make an odd number and rotations that make an even number. If the number N is 123 its rotations would be 123, 321, 132. The odd rotations are 123 and 321 ( 2 ) and even rotation is 132 ( 1 ).
Let us understand with examples.
Input − N= 54762
Output −
Count of rotations of N which are Odd are − 2
Count of rotations of N which are Even are − 3
Explanation − Rotations are −
54762, 25476, 62547, 76254, 47625.
Even rotations are 3 − 54762, 25476, 76254
Odd rotations are 2 − 62547, 47625
Input − N= 3571
Output
Count of rotations of N which are Odd are − 4
Count of rotations of N which are Even are − 0
Explanation − Rotations are −
3571, 1357, 7135, 5713
Even rotations are 0 −
Odd rotations are 4 − 3571, 1357, 7135, 5713
The approach used in the below program is as follows
The number is odd or even can be checked using the unit digits as odd/even. While rotation of a number, all digits would come as unit digits. So we will divide the number by 10 and check if the unit digit is even/odd and increment respective counts.
Take the number as integer N.
Function Even_Odd_rotation(int N) takes the number N and prints the count of odd and even rotations.
Take the initial counts as Even_rotation and Odd_rotation.
Using do-while loop take value=N%10 for unit digit.
If value%2==0, it is even increment Even_rotation, else increment Odd_rotation
Reduce N by 10 for the next unit digit.
Print Even_rotation as rotations of N which are even.
Print Odd_rotation as rotations of N which are even.
Example
#include <bits/stdc++.h>
using namespace std;
void Even_Odd_rotation(int N){
int Even_rotation = 0;
int Odd_rotation = 0;
do{
int value = N % 10;
if(value % 2 == 1)
{ Odd_rotation++; }
else
{ Even_rotation++; }
N = N / 10;
} while(N != 0);
cout<<"Count of rotations of N which are Odd are: "<<Odd_rotation;
cout<<"\nCount of rotations of N which are Even are: "<<Even_rotation;
}
int main(){
int N = 341;
Even_Odd_rotation(N);
return 0;
}
Output
If we run the above code it will generate the following output −
Count of rotations of N which are Odd are: 2 Count of rotations of N which are Even are: 1