1.交换数组
将数组A中的内容和数组B中的内容进行交换。(数组大小一样)
#include <stdio.h>void swap(int arr1[],int arr2[], int sz)
{int tmp = 0;for (int i = 0;i < sz;i++){tmp = arr1[i];arr1[i] = arr2[i];arr2[i] = tmp;}
}void print(int arr1[], int arr2[], int sz)
{for (int i = 0;i < sz;i++){printf("%d ", arr1[i]);}printf("\n");for (int i = 0;i < sz;i++){printf("%d ", arr2[i]);}
}int main()
{int arr1[] = { 3,13,23,33,43,53,63,73,83,93 };int arr2[] = { 2,12,22,32,42,52,62,72,82,92 };int sz = sizeof(arr1) / sizeof(arr1[0]);swap(arr1, arr2, sz);print(arr1, arr2, sz);return 0;
}
2.统计二进制中1的个数
写一个函数返回参数二进制中1的个数。
如:15 0000 1111 4个1
#include <stdio.h>//int Number(int b)
//{
// int count = 0;
// while (b)
// {
// if (b % 2 == 1)
// {
// count++;
// }
// b = b / 2;
// }
// return count;
//}int Number(int b)
{int count = 0;int i = 0;for (i = 0;i < 32;i++){if(((b >> i) & 1 )== 1){count++;}}return count;
}int main()
{int a = -1;//10000000 00000000 00000000 00000001 原码//11111111 11111111 11111111 11111110 反码//11111111 11111111 11111111 11111111 补码int ret = Number(a);printf("%d\n", ret);return 0;
}
3.交换两个变量(不创建临时变量)
不允许创建临时变量,交换两个整数的内容
#include <stdio.h>int main()
{int a = 10;int b = 20;printf("%d %d\n", a, b);a = a ^ b;b = a ^ b;a = a ^ b;printf("%d %d\n",a, b);return 0;
}
4.打印菱形
#include <stdio.h>int main()
{int i = 0;int line = 0;scanf("%d", &line);for (i = 0; i < line; i++){int j = 0;for (j = 0; j<line -1 - i; j++){printf(" ");}for (j = 0; j < 2 * i + 1; j++){printf("*");}printf("\n");}for (i = 0; i < line - 1; i++){int j = 0;for (j = 0; j <= i; j++){printf(" ");}for (j = 0; j < 2 * (line - 1 - i) - 1; j++){printf("*");}printf("\n");}return 0;
}
5.字符串左旋
题目内容:实现一个函数,可以左旋字符串中的k个字符。
例:
ABCD左旋一个字符得到BCDA
ABCD左旋两个字符得到CDAB
#include <stdio.h>void string_left_rotate(char* str, int k)
{int i = 0;int len = strlen(str);for (i = 0; i < k; i++){char tmp = *str;int j = 0;for (j = 0; j < len - 1; j++){*(str + j) = *(str + j + 1);}*(str + len - 1) = tmp;}
}int main()
{char arr[] = "ABCD";int k = 1;string_left_rotate(arr, k);printf("%s\n", arr);return 0;
}