关于C语言的几道题

1.一个数组中只有两个数字是出现一次,其他所有数字都出现了两次。找出这两个数字,编程实现。
#include <stdio.h>
#include <windows.h>
#include <assert.h>
void find_data(int a[], int sz)
{
	assert(a);
	assert(sz > 0);
	int i = 0;
	int num = 0;
	int num1 = 0;
	int num2 = 0;
	int flag = 0;
	//整体异或
	for (i=0; i < sz; i++)
	{
		num ^= a[i];
	}
	//异或得到后的数从最低位开始查找为1的比特位
	for (i=0; i < 32; i++)
	{
		if (((a[i] >> flag) & 1) != 1)
		{
			flag++;
		}
		else
		{
			break;
		}
	}
	//按指定的比特位是否为1来进行分组并分别对每组进行异或查找出每组中单独出现的数
	for (i = 0; i < sz; i++)
	{
		if (((a[i] >> flag) & 1) == 1)
		{
			num1 ^= a[i];
		}
		else
		{
			num2 ^= a[i];
		}
	}
	printf("%d,%d\n", num1, num2);

}
int main()
{
	int arr[] = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 7 };
	find_data(arr, sizeof(arr) / sizeof(arr[0]));
	system("pause");
	return 0;
}
2.喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以喝多少瓶汽水。编程实现。
#include <stdio.h>
#include <windows.h>
#pragma warning(disable:4996)
int bottle(unsigned money)
{
	int count = money;
	int empty = money;
	while (empty >1)
	{
		count += empty / 2;
		empty = empty / 2 + empty % 2;
	}
	return count;
}
int main()
{
	unsigned int money = 0;
	printf("Please Enter:");
	scanf("%u", &money);
	printf("%d", bottle(money));
	system("pause");
	return 0;
}
3.模拟实现strcpy。
#include <stdio.h>
#include <windows.h>
#include <assert.h>
#pragma warning(disable:4996)
char *strcpy(char *dst,const char *src)
{
	char *ret = dst;
	assert(dst);
	assert(src);
	while (*dst++ = *src++)
	{
		;
	}
	return ret;
}

int main()
{
	char str1[] = "abcdef";
	char str2[10];
	printf("%s\n",strcpy(str2,str1));
	system("pause");
	return 0;
}
4.模拟实现strcat
#include <stdio.h>
#include <windows.h>
#include <assert.h>
#pragma warning(disable:4996)
char *strcat(char *dst, const char *src)
{
	char *ret = dst;
	assert(*dst);
	assert(*src);
	//遍历dst字符串直到"\0"
	while (*dst)
	{
		dst++;
	}
	//将src中的字符串拷贝到dst中
	while (*dst++ = *src++)
	{
		;
	}
	return ret;
}
int main()
{
	char str1[] = "abcd";
	char str2[]="1234";
	printf("%s\n", strcat(str2, str1));
	system("pause");
	return 0;
}



猜你喜欢

转载自blog.csdn.net/bit666888/article/details/78554525