在 C 程式中列印 n 個 0 和 m 個 1,使沒有兩個 0 在一起,也沒有三個 1 在一起
n 個 0 和 m 個 1 應按順序排列,這樣形成的序列不能包含兩個連續的 0 和三個連續的 1。
輸入 − N=5 M=9
輸出 − 1 1 0 1 1 0 1 1 0 1 0 1 0 1
注意 − 若要生成上述序列,則語句 (m < n-1) || m >= 2 * (n + 1) 應為 false,如果為 true,則無法生成上述序列。
建議先了解問題邏輯,然後自己嘗試,而不是直接跳轉到下面給出的解決方案。
演算法
START Step 1 -> take values in ‘n’ and ‘m’ Step 2 -> Loop IF m=n-1 Loop While m>0 and n>0 Print 01 Decrement m and n by 1 End Loop While Loop IF n!=0 Print 0 End IF Loop IF m!=0 Print 1 End IF Step 3-> Else (m < n-1) || m >= 2 * (n + 1) Print cn’t have sequence for this Step 4 -> Else Loop While m-n > 1 && n > 0 Print 1 1 0 Decrement m by 2 and n by 1 End While Loop While n>0 Print 1 0 Decrement m and n by 1 End While Loop While m>0 Print 1 Decrement m by 1 End While Step 5-> End Else STOP
示例
#include <stdio.h> #include <math.h> int main() { int n =5, m=9; if( m == n-1 ) { //If m is 1 greater than n then consecutive 0's and 1's while( m > 0 && n > 0 ) { //Loop until all m's and n's printf("01"); m--; n--; } if ( n!=0 ) //Print the remaining 0 printf("0"); if( m!=0 ) //Print the remaining 1 printf("1"); } else if ( (m < n-1) || m >= 2 * (n + 1) ) { //If this is true the sequence can't be made printf("Can't have sequence for this
"); } else { while( m-n > 1 && n > 0 ) { printf("1 1 0 "); m -= 2; n--; } while ( n > 0 ) { printf("1 0 "); n--; m--; } while ( m > 0 ) { printf("1 "); m--; } } return 0; }
輸出
如果我們執行上述程式,它將生成以下輸出。
1 1 0 1 1 0 1 1 0 1 0 1 0 1
廣告