Browse Source

增加了部分题目

Pchen. 5 months ago
parent
commit
8eec834dbb
3 changed files with 128 additions and 0 deletions
  1. 65 0
      code/删除重复字符排序字符串.c
  2. 20 0
      code/整数各位数字求和.c
  3. 43 0
      code/求差集.c

+ 65 - 0
code/删除重复字符排序字符串.c

@@ -0,0 +1,65 @@
+#include <stdio.h>
+#include <string.h>
+
+// 辅助函数:交换两个字符
+void swap(char *a, char *b) {
+    char temp = *a;
+    *a = *b;
+    *b = temp;
+}
+
+// 辅助函数:快速排序
+void quicksort(char arr[], int low, int high) {
+    if (low < high) {
+        int pivot = arr[high];
+        int i = (low - 1), j;
+        for (j = low; j < high; j++) {
+            if (arr[j] < pivot) {
+                i++;
+                swap(&arr[i], &arr[j]);
+            }
+        }
+        swap(&arr[i + 1], &arr[high]);
+        int pi = i + 1;
+        
+        quicksort(arr, low, pi - 1);
+        quicksort(arr, pi + 1, high);
+    }
+}
+
+int main() {
+    char input[1000];
+    char output[1000];
+    
+    // 读取输入字符串
+    if (fgets(input, sizeof(input), stdin) == NULL) {
+        printf("\n");
+        return 0;
+    }
+    
+    // 去掉换行符
+    input[strcspn(input, "\n")] = 0;
+
+    int len = strlen(input);
+    if (len == 0) {
+        printf("\n");
+        return 0;
+    }
+
+    // 对字符串进行快速排序
+    quicksort(input, 0, len - 1);
+
+    // 删除重复字符
+    int j = 0, i;
+    for (i = 0; i < len; i++) {
+        if (i == 0 || input[i] != input[i - 1]) {
+            output[j++] = input[i];
+        }
+    }
+    output[j] = '\0';
+
+    // 输出结果
+    printf("%s\n", output);
+
+    return 0;
+}

+ 20 - 0
code/整数各位数字求和.c

@@ -0,0 +1,20 @@
+#include <stdio.h>
+
+int sum(int x) {
+	int result = 0;
+	while(x > 0) {
+		result += x % 10;
+		x /= 10;
+	}
+	
+	return result;
+}
+
+int main() {
+	int x;
+	scanf("%d", &x);
+	
+	printf("%d", sum(x));
+	
+	return 0;
+}

+ 43 - 0
code/求差集.c

@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+#define MAX_SIZE 100
+
+int main() {
+    int num;
+    int A[MAX_SIZE], B[MAX_SIZE], C[MAX_SIZE];
+    int sizeA = 0, sizeB = 0, sizeC = 0;
+    
+    // 读取集合A
+    while (scanf("%d", &num) == 1 && num != -1) {
+        A[sizeA++] = num;
+    }
+    
+    // 读取集合B
+    while (scanf("%d", &num) == 1 && num != -1) {
+        B[sizeB++] = num;
+    }
+    
+    // 计算差集 A - B
+    int i, j, found;
+    for (i = 0; i < sizeA; i++) {
+        found = 0;
+        for (j = 0; j < sizeB; j++) {
+            if (A[i] == B[j]) {
+                found = 1;
+                break;
+            }
+        }
+        if (!found) {
+            C[sizeC++] = A[i];
+        }
+    }
+    
+    // 输出差集
+    for (i = 0; i < sizeC; i++) {
+        if (i > 0) printf(" ");
+        printf("%d", C[i]);
+    }
+    printf("\n");
+
+    return 0;
+}