这个帖子可能会长期更新。
1.写一个宏,计算结构体中某变量相对于首地址的偏移,其实就是模拟实现offsetof
#define OFFSETOF(st_type, mem_name) (size_t)&(((st_type*)0)->mem_name)
2.写一个宏,可以将一个整数的二进制位的奇数位和偶数位交换。
#define SWAP(num) (num = (((num&0x55555555)<<1)+((num&0xaaaaaaaa)>>1)))
3.请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。(很经典)
class Solution {
public:
void replaceSpace(char* str, int length) {
//数空格
int spacecnt = 0;
char* p = str;
while (*p)
{
if (*p == ' ')
spacecnt++;
p++;
}
int newlen = length + 2 * spacecnt;
int end1 = length - 1;
int end2 = newlen - 1;
while (end1 != end2)
{
if (str[end1] != ' ')
{
str[end2--] = str[end1--];
}
else
{
str[end2--] = '0';
str[end2--] = '2';
str[end2--] = '%';
end1--;
}
}
}
};
4.Fibonacci数列是这样定义的:
F[0] = 0
F[1] = 1
for each i ≥ 2: F[i] = F[i-1] + F[i-2]
因此,Fibonacci数列就形如:0, 1, 1, 2, 3, 5, 8, 13, ...,在Fibonacci数列中的数我们称为Fibonacci数。给你一个N,你想让其变为一个Fibonacci数,每一步你可以把当前数字X变为X-1或者X+1,现在给你一个数N求最少需要多少步可以变为Fibonacci数。
#include <stdio.h>
#include <math.h>
int main()
{
int a = 0;
int b = 1;
int c = 1;
int n = 0;
scanf("%d", &n);
while (1)
{
if (b == n)
{
printf("0\n");
break;
}
else if (b > n)
{
if (abs(a - n) > abs(b - n))
{
printf("%d\n", abs(b - n));
}
else
{
printf("%d\n", abs(a - n));
}
break;
}
a = b;
b = c;
c = a + b;
}
return 0;
}
5.写一个程序,判断当前机器大小端。
这个题前面写过,两种解法
C语言深度解析之一:数据存储_何以过春秋的博客-CSDN博客
C语言深度解析之六:自定义类型详解(结构体+枚举+联合)_何以过春秋的博客-CSDN博客
更多推荐
C语言笔试经典编程题目(汇总帖)
发布评论