喝汽水问题, 1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以喝多少瓶汽水

1.喝汽水问题, 1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以喝多少瓶汽水

思路:

首先进行如图所示的第一列操作,当为0个瓶子时,开始第二列的计算(用空瓶子数来换汽水)重复上面的操作,直到只有一个空瓶时返回0。


int A(int n, int y)
{
	if(n==0)//汽水喝完,开始用空瓶子来换汽水
	{
		if(y <= 1)
		{
			return 0;
		}
		else
		{
			//计算多余出来瓶子的个数
			int i = 0;
			int j = 0;
			while(y)//计算喝完之前多出来多少个空瓶
			{
				if(y%2 != 0)
					i++;
				y = y/2; 
			}
			j = i;
			i= i/2;
			return i+A(i/2, j);
		}
	}
	else
	{
	    return n+A(n/2,y);
    }

    
}


int main()
{
	int x = 0;
	int y = 0;
	scanf("%d", &x);
	y = A(x, x);
	printf("%d", y);
	system("pause");
	return 0;
}
2.在一个数组中只有两个数数字出现一次,其他的都出现两次,找出这两个数
#include<stdio.h>
#include<stdlib.h>

void Find(int arr[],int c[],int n)
{
        int i = 0;
	int j = 0;
	int b[10] = {0};//用来记录数组a中数组是否成对存在
	for(i = 0; i < n; i++)//遍历数组a,把它的值做为数组b的下标
	{
		int x = arr[i];
		if(b[x] == 0)//第一次出现记为1
		{
			b[x]+=1;
		}
		else//第二次出现记为0
		{
			b[x]-=1;
		}
	}
	for(i = 0; i < 10; i++)//对数组b遍历,找到数组b中哪两个下标对应的值不为0
	{
        if(b[i] != 0)
		{
			c[j] = i;//将这两个数存入数组c中
			j++;
		}
	}
}


int main()
{
	int i = 0;
	int c[2] = {0};//用来存储那两个只出现了一次的数字
	int a[] = {1,2,3,4,5,6,4,3,2,1,0,0};
       Find(a,c,sizeof(a)/sizeof(a[0]));
	for(i = 0; i < 2; i++)
	printf("%d ", c[i]);
	system("pause");
	return 0;
}

3.实现strcpy函数

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

char* My_strcpy(char *n_a, const char *n_b)
{
	char *p = n_a;//将首地址保存,防止找不到
	assert(n_a);
	assert(n_b);
        while(*n_a = *n_b)
	{		
		n_a++;
		n_b++;
	}
	return p;
}

int main()
{
	char *a = "AWEDFGTYGH";
	char b[] = "0";
	char *p = My_strcpy(b, a);

    printf("%s", p);
	system("pause");
	return 0;
}

4.实现strcat函数

 
 
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

char* My_strcat(char n_a[], char *n_b)
{
	int i = 0;
	char *ret = n_a;
	assert(n_a);
	assert(n_b);
	while(n_a[i] != '\0')
	{
                i++;
	}
	while(n_a[i] = *n_b)
	{
                i++;
		n_b++;
	}
	return ret;
}

int main()
{
	char a[] = "AWEDFGTYGH";
	char b[] = "ASDDDDFG";
	char *p = My_strcat(a, b);
    printf("%s", p);
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/ksaila/article/details/80212831