编程练习#4

1.一个数组中只有两个数字是出现一次, 
其他所有数字都出现了两次。 
找出这两个数字,编程实现。 
 

#include<stdio.h>
int seach(int* p, int num){
	int i = 0;
	for (i = 0; i < num - 1; i++){
		//用第一位与后面的数全部进行异或运算
		//活用两个相同的数异或运算为0的特性
		//最终可以把单独的那个数保留下来
		*p = *p ^ *(p + i + 1);
	}
	return *p;
}
int main(void){
	int ch[] = { 1, 2, 4, 5, 3, 1, 2, 3, 5, 9 };
	int arr[10] = { 0 };
	int num = 0;
	int record = 0;
	num = sizeof(ch) / sizeof(ch[0]);
	int text = 0;
	//用一个循环寻找异或后的第一个为1的二进制位(第一个不相同的位)

	text = seach(ch, num);//两个单独数异或结果

	for (int i = 0; i < 32; i++){
		if ((text >> i) == 1){
			record = i;//记录该位在二进制的位置
			break;
		}
	}

	for (int j = 0; j < num; j++){
		if ((ch[j] >> record) == 1){
			arr[j] = ch[j];
		}
	}
	int put = seach(arr, num);
	//这里要一个临时变量put来储存seach的结果
	//因为第一次调用的时候已经将原来的ch数组破坏了,所以不能反复调用seach数组
	printf("%d\n",put);	
	printf("%d\n", put ^ text);
	return 0;
}


2.喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水, 
给20元,可以多少汽水。 
编程实现。 
 

#include<stdio.h>
int main()
{
	int full = 20;
	int num = full;
	int empty = full;
	while (empty >= 0)
	{
		num =num + empty / 2;
		empty = empty / 2 + empty % 2;
		if (empty == 1){
			printf("%d\n", num + 1);
			//当手上只有一个空瓶时可以向老板借一瓶然后再还两个空瓶子
			return 0;
		}
	}
	printf("%d\n", num);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值