写一个算法,比较两个字符串中所包含的每个字符的个数否相同:
例如:
“ASDFG”, “SAGFD”, return true;
“AADFG”, “ASDFG”, return false;
#include <iostream> #include <string> using namespace std; bool compare( string &str1, string &str2) { char *pos1 = (char *)str1.c_str(); char *pos2 = (char *)str2.c_str(); char *pos = pos1; if(strlen(str1.c_str()) != strlen(str2.c_str())){ return false; } for(int i = 0; i < strlen(str1.c_str()); ++i){ int number1 = 0, number2 = 0; for(int j = 0; j < strlen(str2.c_str()); ++j){ if(*pos2 == *pos1){ number2++; } pos2++; } pos2 = (char *)str2.c_str(); for(int k = 0; k < strlen(str1.c_str()); ++k){ if(*pos == *pos1){ number1++; } pos++; } pos = (char *)str1.c_str(); pos1++; if(number1 == number2){ continue; } else{ return false; } } return true; } int main() { string str1 = "ABCDEFG"; string str2 = "ACDBEGF"; bool isEqual = compare(str1, str2); if(isEqual){ cout<<"return True!"<<endl; } else{ cout<<"return False!"<<endl; } return 0; }
感谢网友 HelloVisaya 提供的排序后再比较的想法,实现出来比较简单了。
#include <iostream> #include <string> #include <algorithm> using namespace std; bool compare( string &str1, string &str2) { if(strlen(str1.c_str()) != strlen(str2.c_str())){ return false; } sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); if(str1 == str2){ return true; } else{ return false; } } int main() { string str1 = "2ABCDEFG"; string str2 = "2CDBEGFA"; bool isEqual = compare(str1, str2); if(isEqual){ cout<<"return True!"<<endl; } else{ cout<<"return False!"<<endl; } return 0; }
计算N个数字,从1到N每个数字的阶乘的和:
例如:sum = 1! + 2! + 3! + ...+ N!.
#include <iostream> using namespace std; int factorial(int n) { int factValue = 1; for(int i = 1; i <= n; ++i) { factValue = factValue * i; } return factValue; } int factorialSum(int n) { int sum = 0; while(n > 0){ sum += factorial(n); --n; } return sum; } int main() { int factSum = factorialSum(3); cout<<factSum <<endl; }