1. 程式人生 > >一個數組中只有兩個數字是出現一次,其他所有數字都出現了兩次。 找出這兩個數字,程式設計實現。

一個數組中只有兩個數字是出現一次,其他所有數字都出現了兩次。 找出這兩個數字,程式設計實現。

1.一個數組中只有兩個數字是出現一次,其他所有數字都出現了兩次。 找出這兩個數字,程式設計實現。

#include<stdio.h>
#include<stdio.h>
int main()
{
	int arr[] = { 1, 3, 8, 1, 3, 8, 4, 6 };
	int num = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	int i = 0;
	int pos = 0;
	int x = 0;
	int y = 0;
	for (i = 0; i < sz; i++)
	{
		num ^= arr[i];
	}
	printf("num=%d\n");
	//找num二進位制中為1的一個位pos
	for (i = 0; i < 32; i++)
	{
		if (1 == ((num >> i) & 1))
		{
			pos = i;
			break;
		}
	}
	for (i = 0; i < sz; i++)
	{
		if (((arr[i] >> pos) & 1) == 1)
		{
			x ^= arr[i];
		}
		else
		{
			y ^= arr[i];
		}
	}
	printf("x=%d y=%d", x, y);
	system("pause");
	return 0;
}

2.喝汽水,1瓶汽水1元,2個空瓶可以換一瓶汽水,給20元,可以多少汽水。程式設計實現。

#include<stdio.h>
int main()
{
	int money = 0;
	int total = 0;//能喝的瓶數
	int empty = 0;//空瓶個數
	scanf_s("%d", &money);
	total = money;
	empty = money;
	while (empty > 1)
	{
		total += empty / 2;
		empty=empty / 2+empty%2;
	}
	printf("total=%d", total);
	system("pause");
	return 0;
}