Alternating Numbers | C ++ program for the above approach ; Function to check if a string is of the form even odd even odd ... ; Function to check if a string is of the form odd even odd even ... ; Function to check if n is an alternating number ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isEvenOddForm ( string s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 && s [ i ] % 2 != 0 ) return false ; if ( i % 2 == 1 && s [ i ] % 2 != 1 ) return false ; } return true ; } bool isOddEvenForm ( string s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 && s [ i ] % 2 != 1 ) return false ; if ( i % 2 == 1 && s [ i ] % 2 != 0 ) return false ; } return true ; } bool isAlternating ( int n ) { string str = to_string ( n ) ; return ( isEvenOddForm ( str ) || isOddEvenForm ( str ) ) ; } int main ( ) { int N = 129 ; if ( isAlternating ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }