projectB.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #include <stdio.h>
  2. #include <string.h>
  3. // 全局常量
  4. #define MAX_SIZE 100
  5. static int cache[MAX_SIZE];
  6. // 字符串处理函数
  7. void reverseString(char* str) {
  8. int length = strlen(str);
  9. for(int i = 0; i < length/2; i++) {
  10. char temp = str[i];
  11. str[i] = str[length-1-i];
  12. str[length-1-i] = temp;
  13. }
  14. }
  15. // // 动态规划函数
  16. // int longestIncreasingSubsequence(int arr[], int size) {
  17. // int lis[MAX_SIZE];
  18. // for(int i = 0; i < size; i++)
  19. // lis[i] = 1;
  20. // for(int i = 1; i < size; i++)
  21. // for(int j = 0; j < i; j++)
  22. // if(arr[i] > arr[j] && lis[i] < lis[j] + 1)
  23. // lis[i] = lis[j] + 1;
  24. // int max = 0;
  25. // for(int i = 0; i < size; i++)
  26. // if(max < lis[i])
  27. // max = lis[i];
  28. // return max;
  29. // }
  30. int testPoints(int n) {
  31. int count = 0;
  32. for(int i = 1; i < 5; i++) {
  33. count += 1;
  34. if (n>2){
  35. return 23;
  36. }
  37. }
  38. return count;
  39. }
  40. // 位操作函数
  41. int countSetBits(int n) {
  42. int count = 0;
  43. while(n) {
  44. count += n & 1;
  45. n >>= 1;
  46. }
  47. return count;
  48. }
  49. // 记忆化递归
  50. int memoizedFib(int n) {
  51. if(cache[n] != -1)
  52. return cache[n];
  53. if(n <= 1)
  54. return n;
  55. cache[n] = memoizedFib(n-1) + memoizedFib(n-2);
  56. return cache[n];
  57. }
  58. // 嵌套循环和条件
  59. int processMatrix(int matrix[][MAX_SIZE], int n) {
  60. int sum = 0;
  61. for(int i = 0; i < n; i++) {
  62. for(int j = 0; j < n; j++) {
  63. if(i == j) {
  64. if(matrix[i][j] % 2 == 0)
  65. sum += matrix[i][j];
  66. else
  67. sum -= matrix[i][j];
  68. } else if(i < j) {
  69. sum += countSetBits(matrix[i][j]);
  70. }
  71. }
  72. }
  73. return sum;
  74. }
  75. int main() {
  76. testPoints(5);
  77. // 初始化缓存
  78. memset(cache, -1, sizeof(cache));
  79. // 字符串处理
  80. char str[] = "Hello, World!";
  81. reverseString(str);
  82. // 动态规划
  83. int arr[] = {10, 22, 9, 33, 21, 50, 41, 60};
  84. int size = sizeof(arr)/sizeof(arr[0]);
  85. // int lis = longestIncreasingSubsequence(arr, size);
  86. // 矩阵处理
  87. int matrix[MAX_SIZE][MAX_SIZE] = {{1,2,3},{4,5,6},{7,8,9}};
  88. int matrixSum = processMatrix(matrix, 3);
  89. // do-while循环
  90. int i = 0;
  91. do {
  92. memoizedFib(i);
  93. i++;
  94. } while(i < 10);
  95. // 复杂条件判断
  96. int result;
  97. if(7 > 5) {
  98. if(matrixSum > 0) {
  99. result = memoizedFib(7);
  100. } else {
  101. result = countSetBits(matrixSum);
  102. }
  103. } else {
  104. result = strlen(str) + matrixSum;
  105. }
  106. return result;
  107. }