xx校园招聘编程题 : n级台阶、String类、数据交换并排序

xxx2016年校园招聘编程题 : n级台阶、String类、数据交换并排序

1、n级台阶
n级台阶,可以跳1级,也可以跳2级,总共有多少总跳法?
算法思想:算法为fun(n)
(1)当只有1级时,跳1级,只有1种方法;
(2)当只有2级时,可以只跳1级,也可以一次跳2级,总共有2种方法
(3)当为n>2级时,第1级跳1级,剩下的n-1级台阶跳法有fun(n-1);第一级跳2级时,剩下的n-2级跳法有fun(n-2)种。     
 
即fun(n)=fun(n-1)+fun(n-2).为Fibonacci数列.

</pre><pre name="code" class="cpp">int FunSteps(int n)
{
	if(n==1||n==2)
		return n;
	else
		return FunSteps(n-1)+FunSteps(n-2);
}

2、String类函数

#include<iostream>
#include<string>
using namespace std;

class String
{
    private:
		char *m_data;
    public:
		String(const char *str=NULL);
		String(const String &another);
		String & operator=(const String &rhs);
		~String();
		void print();

};
//返回值类型 类名::函数名(参数)
String::String(const char *str)
{
	if(str)
	{
		m_data=new char[strlen(str)+1];
		strcpy(m_data,str);
	}
	else
	{
		m_data=new char[1];
		*m_data='\0';
	}
}
//新变量的拷贝构造函数
String::String(const String &another)  
{
	if(another.m_data)
	{
		m_data=new char[strlen(another.m_data)+1];
		strcpy(m_data,another.m_data);
	}
	else
	{
		m_data=new char[1];
		*m_data='\0';
	}	
}
//已有变量的=重载
String & String::operator=(const String &rhs)
{
	if(this==&rhs)
		return *this;
	if(m_data)
		delete [] m_data;
	if(rhs.m_data)
	{
		m_data=new char[strlen(rhs.m_data)+1];
		strcpy(m_data,rhs.m_data);
	}
	else
	{
		m_data=new char[1];
		*m_data='\0';
	}
	return *this;
}
//析构函数
String::~String()
{
	if(m_data)
		delete [] m_data;
}
//输出
void String::print()
{
	cout<<m_data;
}


int main(void)
{
	String c("ok");
	c.print();
	String c1=c;  //拷贝构造函数
	c1.print();
	String c2;
	c2=c;      //=重载函数
	c2.print();

	return 0;
}
3、数据交换并排序
n个乱序的数,其中只能有0与其他任何位置的数SWAP(交换),编程实现升序排序

考试时候没有时间了,读题没有读懂,后面经同学指点,应该是比较交换只能是下标为0的位置和其他任何位置交换,

即应该是冒泡法的排序思想:

#include<iostream>
using namespace std;

void bubble(int *a,int n)
{
	int t;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n-1-i;j++)
		{
			if(a[j]>a[0])
			{
				t=a[j];
				a[j]=a[0];
				a[0]=t;
			}
		}
		t=a[0];
		a[0]=a[n-1-i];
		a[n-1-i]=t;
	}
}

int main(void)
{
	int a[10]={2,10,11,9,1,4,9,8,5,6};

	bubble(a,10);

	for(int i=0;i<10;i++)
		cout<<a[i]<<" " ;
	cout<<endl;


	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值