递归----练习17(2)
1.
题目描述
KiKi和BoBo玩 “井”字棋。也就是在九宫格中,只要任意行、列,或者任意对角线上面出现三个连续相同的棋子,就能获胜。请根据棋盘状态,判断当前输赢。
输入描述:
三行三列的字符元素,代表棋盘状态,字符元素用空格分开,代表当前棋盘,其中元素为K代表KiKi玩家的棋子,为O表示没有棋子,为B代表BoBo玩家的棋子。
输出描述:
如果KiKi获胜,输出“KiKi wins!”;
如果BoBo获胜,输出“BoBo wins!”;
如果没有获胜,输出“No winner!”。
#include <iostream> using namespace std; int main() { char a[3][3] = {0}; int state = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cin >> a[i][j]; } } if (a[0][0] == a[1][1] && a[0][0] == a[2][2] && a[1][1] != 'O') { if(a[1][1]=='K') { cout << "KiKi wins!" << endl; state = 1; } else if (a[1][1] == 'B') { cout << "BoBo wins!" << endl; state = 1; } } if (a[2][0] == a[1][1] && a[1][1] == a[0][2] && a[1][1] != 'O') { if (a[1][1] == 'K') { cout << "KiKi wins!" << endl; state = 1; } else if (a[1][1] == 'B') { cout << "BoBo wins!" << endl; state = 1; } } for (int i = 0; i < 3; i++) { if (a[0][i] == a[1][i] && a[1][i] == a[2][i] && a[0][i] != '0') { if (a[1][i] == 'K') { cout << "KiKi wins!" << endl; state = 1; } if (a[1][i] == 'B') { cout << "BoBo wins!" << endl; state = 1; } } } for (int i = 0; i < 3; i++) { if (a[i][0] == a[i][1] && a[i][1] == a[i][2] && a[i][0] != '0') { if (a[i][1] == 'K') { cout << "KiKi wins!" << endl; state = 1; } if (a[i][2] == 'B') { cout << "BoBo wins!" << endl; state = 1; } } } if (state == 0) { cout << "No winner!" << endl; } }
2.阶乘计算
#include <iostream> using namespace std; long long jiecheng (int n) { if (n > 1) { return n * jiecheng(n - 1); } else if (n == 1) { return 1; } return 0; } int main() { int n; cin >> n; cout << jiecheng(n) << endl; }
注意此题要用long long,否则取值范围不够
3.快速排序
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n; cin >> n; int* p = new int[n]; for (int i = 0; i < n; i++) { cin >> p[i]; } sort(p, p + n); for (int i = 0; i < n; i++) { cout << p[i] << " "; } }
4.素数判断
题目描述:
输入一个正整数n,接下来输入n行,每行是一个正整数。判断其是否是素数,并打印出其所有质因数。
#include <iostream> using namespace std; int ss1(int x); void ss2(int x); int main() { int n,x; cin>>n; for(int i=0;i<n;i++) { cin>>x; if(ss1(x)) { cout<<"isprime"<<endl; } else { cout<<"noprime"<<endl; } ss2(x); cout<<endl; } } int ss1(int x) { if(x<2) {return 0;} if(x==2||x==3) {return 1;} for(int i=2;i*i<=x;i++) { if(x%i==0) { return 0; } } return 1; } void ss2(int x) { for(int i=2;i*i<=x;i++) { int state=0; while(x%i==0) { if(state==0) { cout<<i<<" "; state=1; } x/=i; } } if(x>1) {cout<<x<<" ";} }