常見面試程序題

1、 給定排好序的數組A(從小到大),大小爲n,現在給定數X,插入到給定的數組A中,保持排序(二分法)。

主要考察二分法。

#include "stdafx.h"
#include <iostream>

using namespace std;
#define Max 10
int BinaryFind(int a[],int n,int insertNum);

int _tmain(int argc, _TCHAR* argv[])
{
	int a[Max]={1,2,3,4,5,8,10};
	int insertNum=6;
	int pos=BinaryFind(a,7,insertNum);
	
	for(int i=7-1;i>=pos;i--)
		a[i+1]=a[i];

	a[pos]=insertNum;

	system("pause");
	return 0;
}

//二分法查找要插入的位置  a數組是從小到大的有序數組
int BinaryFind(int a[],int n,int insertNum)
{
	int left=0;
	int right=n-1;
	int mid;
	while(left<right)
	{
		mid=left+(right-left)/2;

		if(a[mid]>insertNum)
		{
			right=mid-1;
		}
		else if(a[mid]<insertNum)
		{
			left=mid+1;
		}
		else
		{
			return mid;
		}

	}
	return mid;
}


 

2. 寫一個棧的實現,並將1-10入棧和出棧

#include "stdafx.h"
#include <iostream>

using namespace std;
#define Max 100

typedef struct stack
{
	int data[Max];
	int top; //棧頂指針
}Seqtack,*SStack;

void InitStack(SStack s);
void Push(SStack s,int data);
int Pop(SStack s);


int _tmain(int argc, _TCHAR* argv[])
{

	SStack s;
	s=(SStack)malloc(sizeof(Seqtack));
	InitStack(s);
	for(int i=1;i<=10;i++)
	{
		Push(s,i);
	}
	
	for(int i=0;i<10;i++)
	{
		int t=Pop(s);
		cout<<t<<"  ";
	}
	system("pause");
	return 0;
}


//初始化順序棧
void InitStack(SStack s)
{
	s->top=-1;
}

//入棧
void Push(SStack s,int data)
{
	//判斷棧是否已滿
	if(s->top>=Max-1)
	{
		cout<<"棧滿,不能入棧!"<<endl;
		exit(-1);
	}
	else
	{
		s->data[++s->top]=data;
	}
}

//出棧
int Pop(SStack s)
{
	//判斷是否爲空
	if(-1==s->top)
	{
		cout<<"爲空棧,不能出棧!"<<endl;
		exit(-1);
	}
	else
	{
		int temp=s->data[s->top--];
		return temp;
	}
}


 

3.編寫一個函數,要求輸入年月日時分秒,輸出下一秒的時間。

#include "stdafx.h"
#include  <iostream>

using namespace std;
void AddSecond(int sec);
int Time[6]; //Time[0]—Time[5]依次表示年、月、日、時、分、秒       24 60 60 
int MonthDay[]={31,28,31,30,31,30,31,31,30,31,30,31}; //12月中每月的天數  爲平年
int _tmain(int argc, _TCHAR* argv[])
{
	for(int i=0;i<6;i++)
	{
		cin>>Time[i];
	}
	AddSecond(1);
	for(int i=0;i<6;i++)
	{
		cout<<Time[i]<<" ";
	}
	system("pause");
	return 0;
}

void AddSecond(int sec)
{
	if((Time[0]%400==0)||((Time[0]%4==0)&&(Time[0]%100!=0))) //如果爲閏年
	{
		MonthDay[1]=29;
	}
	else   //爲平年
	{
		MonthDay[1]=28;
	}
	int n=sec;
	int m=0;

	 //秒
		Time[5]+=n;
		n=Time[5]/60;
		m=Time[5]%60;
		Time[5]=m;
    //分
		Time[4]+=n;
		n=Time[4]/60;
		m=Time[4]%60;
		Time[4]=m;
	//時
	    Time[3]+=n;
		n=Time[3]/24;
		m=Time[3]%24;
		Time[3]=m;
	//天
	    Time[2]+=n;
		n=Time[2]/MonthDay[Time[1]];
		m=Time[2]%MonthDay[Time[1]];
		Time[2]=m;
	//月
		Time[1]+=n;
		n=Time[1]/12;
		m=Time[1]%12;
		Time[1]=m;
	//年
		Time[0]+=n;
}

 

參考來源: lunchenqun http://blog.csdn.net/luchenqun/article/details/6554005
 

發佈了62 篇原創文章 · 獲贊 23 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章