1.一个数组中只有两个数字是出现一次,
其他所有数字都出现了两次。
找出这两个数字,编程实现。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[] = { 9,1,2,3,3,1,4,5,6,7,8,8,7,6,5,9 }; //2 4
int sz = sizeof(arr) / sizeof(arr[0]);
int ret = 0;
int pos = 0;
int x = 0, y = 0;
for (int i = 0; i < sz; ++i)
{
ret ^= arr[i];
}
for (int i = 0; i < 32; ++i)
{
if (1 == ((ret >> i) & 1))
{
pos = i;
break;
}
}
for (int i = 0; i < sz; ++i)
{
if (1 == ((arr[i] >> pos) & 1))
x ^= arr[i];
else
y ^= arr[i];
}
printf("%d %d\n", x, y);
system("pause");
return 0;
}
也可以直接堆数组排序,跟下一个数组元素比较,得到只出现一次的数字。
2.喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,
给20元,可以多少汽水。
编程实现。
#include <stdio.h>
#include <stdlib.h>
int a(int k)
{
int e = k / 2 + k % 2;
if (e > 1)
return k / 2 + a(e);
else
return k / 2;
}
int main()
{
int y = 20;
int k = y;
printf("%d\n", y + a(k));
system("pause");
return 0;
}
3.模拟实现strcpy
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
char *mystrcpy(char *str2, const char *str1)
{
assert(str1 != NULL);
assert(str2 != NULL);
char *r = str2;
while ((*r++ = *str1++) != '\0');
return r;
}
int main()
{
char str1[] = "abcdef";
char str2[] = { 0 };
mystrcpy(str2, str1);
strcpy(str2, str1);
printf("%s\n", str2);
printf("%s\n", str2);
return 0;
}
4.模拟实现strcat
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
char *mystrcat(char *str2, const char *str1)
{
assert(str1);
assert(str2);
char *r = str2;
while (*str2 != '\0')
{
str2++;
}
while (*str2++ = *str1++);
return str2;
}
int main()
{
char str1[] = "def";
char str2[] = "abc";
mystrcat(str2, str1);
strcat(str2, str1);
printf("%s\n", str2);
printf("%s\n", str2);
return 0;
}