一些算法题
1、将一整数逆序后放入一数组中(要求递归实现)
#include <stdio.h> void convert(int *result, int n) { if(n>=10) convert(result+1, n/10); *result = n%10; } int main(int argc, char* argv[]) { int n = 123456789; int result[20]={}; convert(result, n); for(int i=0; i<9; i++) printf("%d", result[i]); getchar(); }
2.求高于平均分的学生学号及成绩(学号和成绩人工输入)
#include <stdio.h> #include <iostream> #include <map> using namespace std; typedef map<int, int> templatemap; templatemap studet ; void find(int &nScore) { int number, score; scanf("%d", &number); if(number != 0) { scanf("%d", &score); studet[number]=score; nScore +=score; find(nScore); } } int main(int argc, char* argv[]) { int nScore = 0; find(nScore); int nAverage = nScore/(studet.size()); for(templatemap::iterator itr = studet.begin(); itr!=studet.end();itr++) { if(nAverage<itr->second) cout<<"ID:"<<itr->first<<" Score:"<<itr->second<<endl; } getchar(); }
3、递归实现回文判断(如:abcdedbca就是回文,判断一个面试者对递归理解的简单程序)
#include <stdio.h> #include <iostream> int find(char *str, int n) { if(n<=1) return 1; if(str[0]==str[n-1]) { return find(str+1, n-2); } else { return 0; } } int main(int argc, char* argv[]) { char *str = "abcdedcba"; printf("%s: %s\n", str, find(str, strlen(str)) ? "Yes" : "No"); getchar(); }
4.分解成质因数(如435234=251*17*17*3*2,据说是华为笔试题)
#include <stdio.h> #include <iostream> void prim(int m, int n) { if(m>n) { while(m%n != 0) n++; m /= n; printf("%d*", n); prim(m, n); } else { printf("%d", m); } } int main(int argc, char* argv[]) { int n = 100; printf("%d=", n); prim(n, 2); getchar(); }