1.实现函数:对一个8bit数据(unsigned char类型)的指定位(例如第n位)的置0或者置1操作,并保持其他位不变,
函数原型:void bit_set(unsigned char *p_data,unsigned char position,int flag)
注:(p_data是指定的源数据,position是指定位(1-8);flag表示是置0还是置1操作)
这道题画个结构图一目了然:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
void bit_set(unsigned char *p_data, unsigned char position, int flag)
{
assert(p_data);
assert((position >= 1) && (position <= 8));
if (flag == 1)
{
*p_data |= (1 << (position - 1));
}
else if (flag == 0)
{
*p_data &= ~(1 << (position - 1));
}
}
int main()
{
unsigned char *p_data = 2;
bit_set(&p_data, 3, 1);
printf("%d\n", p_data);
bit_set(&p_data, 2, 0);
printf("%d\n", p_data);
return 0;
}
2.请实现字符串右循环移位函数,比如:“abcdefhi”循环右移2位就是“hiabcdef”.
函数原型:void RightLoopMove(char *pStr,unsigned short steps)
这道题有两种方法:
First:临时开辟一块空间ret存储最后一个字符,然后把前面的字符依次往后放,再将临时空间里面的字符放到第一个位置,循环两次。
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void RightLoopMove(char *pStr, unsigned short steps)
{
int len = 0;
int i = 0;
int j = 0;
char ret;
assert(pStr);
assert(steps);
len = strlen(pStr);
for (j = 0; j < steps; j++)
{
ret = *(pStr + len - 1);
for (i = 0; i < len - 1; i++)
{
*(pStr + len - 1 - i) = *(pStr + len - 2 - i);
}
*pStr = ret;
}
}
int main()
{
char p[] = { "abcdefghi" };
RightLoopMove(p, 2);
printf("%s\n", p);
return 0;
}
Second:将字符串进行三次翻转
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void Reserve(char *left, char *right)
{
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
void RightLoopMove(char *pStr, unsigned short steps)
{
int len = 0;
assert(pStr);
assert(steps);
len = strlen(pStr);
Reserve(pStr, pStr + len - steps - 1);
Reserve(pStr+len-steps, pStr + len - 1);
Reserve(pStr, pStr + len - 1);
}
int main()
{
char p[] = { "abcdefghi" };
RightLoopMove(p, 2);
printf("%s\n", p);
return 0;
}
3.请编写程序实现字符串到整数的转换,例如:输入字符串“12345”,输出整数12345
这个题目由于字符串不是确定,可能会出现很多情况所以我们应该考虑NULL 空字符串 +- 异常字符 溢出
实际上就是实现atoi函数
enum Status
{
VALID, //合法
INVALID //非法
};
enum Status status = INVALID;
int my_atoi(char *ptr)
{
int flag = 1;
long long ret = 0;
assert(ptr);
if (*ptr == '\0') //NULL
{
return 0;
}
while (isspace(*ptr))//空白字符串
{
ptr++;
}
if (*ptr == '-')//正负数
{
flag = -1;
ptr++;
}
else if (*ptr == '+')
{
ptr++;
}
while (*ptr)//溢出
{
if (isdigit(*ptr))
{
ret = ret * 10 + (flag*(*ptr - '0'));
if (ret == INT_MAX || ret == INT_MIN)
{
if (flag == 1)
{
return INT_MAX;
}
else
{
return INT_MIN;
}
}
}
else
{
return (int)ret;
}
ptr++;
}
status = VALID;
return (int)ret;
}
int main()
{
char p[] = { "12345" };
int num = my_atoi(p);
printf("%d\n", num);
return 0;