笔试题(2)

16 篇文章 0 订阅

(1) 微软面试题目:给定一个整数数组,将数组中小于零的数都放在最左边,等于0的放在中间,小于零的放在最右边。

实现:

void swap(int* a,int* b)
{
	*a = *a ^ *b;	//a、b中不同位
	*b = *a ^ *b;	//b = a
	*a = *a ^ *b;	//a = b
}
void ArrangArray(int* StartPos,int* EndPos)
{
	//Step1先将小于零的放在最左边,大于等于0的数不区分,都放在右边
	int* low = StartPos;
	int* high = EndPos;
	while(low < high)
	{
		while( *low < 0 && low < high ) low++;
		while( *high >= 0 && low < high ) high--;
		if(low < high)
			swap(low,high);
	}
	//循环结束时,low一定等于high,且指向大于等于0的数
	//Step2,从low开始,将等于0的数移动到左边,大于0的数移动到右边
	high = EndPos;
	while(low < high)
	{
		while( *low == 0 && low < high ) low++;
		while( *high > 0 && low < high ) high--;
		if(low < high)
			swap(low,high);
	}
}
int main()
{
	int array[10] = {-1,3,0,2,-5,0,-3,4,0,-8};
	ArrangArray(array,array + 9);
}

(2) 在字符串中找出连续最长的数字串,并把这个串的长度返回;如果长度相同,返回最后一个连续字符串

#include<iostream>
using namespace std;

int main()
{
	char *str = "sabfc1234ei1234";
	char *ptr = str;
	int info_max[2] = {0,0};//记录最长连续数字字符串长度和位置
	int info_temp[2] = {0,0};//记录当前连续数字字符串长度和位置
	while(*ptr != '\0')
	{
		if( *ptr >= '0'&& *ptr <= '9')
		{
			if(info_temp[0] == 0)//当数字长度为0时开始新一轮长度计算
			{
				if( *ptr >= '0'&& *ptr <= '9')//第一个字符记录起始位置
				{
					info_temp[0]++;
					info_temp[1] = ptr - str ; //记录发现数字字符时指针位置
				}
				ptr++;	
				while((*ptr >= '0'&& *ptr <= '9')&& ((*ptr) - *(ptr-1) == 1)&&(*ptr != '\0'))//计算长度和结束位置
				{
					info_temp[0]++;
					ptr++;
				}
				//如果新的数字串长度比最大数字串长度长
				if(info_temp[0] >= info_max[0])
				{
					info_max[0] = info_temp[0];
					info_max[1] = info_temp[1];
				}
				//交换后重新初始化数字串信息
				info_temp[0] = 0;
				info_temp[1] = 0;
			}
		}
		ptr++;
	}
	cout<<"Length:"<<info_max[0]<<endl;
	cout<<"Location:"<<info_max[1] + 1<<endl;
	cout<<"NumberString:";
	for(int i = 0;i< info_max[0];i++)
		cout<<*(str+info_max[1]+i);
	cout<<endl;
	getchar();
	return 1;
}

(3)设计一个洗牌程序

#include<ctime>
const int CARD_COUNT = 54;
size_t shuffle(char s[], int len)
{
	size_t t = 0;
	int i = 0;
	int num;
	while(i < len)
	{
		t++;
		num = rand()%len;
		if (memchr(s,num,i) == NULL)
		/*
		原型:extern void *memchr(void *buf, char ch, unsigned count);

		用法:#include <string.h>
  
		功能:从buf所指内存区域的前count个字节查找字符ch。
  
		说明:当第一次遇到字符ch时停止查找。如果成功,返回指向字符ch的指针;否则返回NULL。
		*/
			s[i++] = num;
	}
	return t;
}

void printCards(char s[], int n)
{
    for (int i=0; i<n; i++)
    {
        cout << static_cast<int>(s[i]) << " ";
    }
    cout << endl;
}

void main()
{
	int n = 0;
	srand((unsigned int)time(NULL));
	while(n++<10)
	{		
		char s[CARD_COUNT];
		int count = shuffle(s, CARD_COUNT);
		printCards(s,CARD_COUNT);
		cout<<"time = "<<count<<endl;
	}
	system("pause");
}






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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值