Classic C + + written questions--100 (programming practice (harder than C) (91-100)) __linux

Source: Internet
Author: User
Tags assert class definition int size


programming exercises (harder than C) (91-100) 91. Write a C function that gives the number of bits in a byte that are placed in 1. "Reference Answer"

unsigned   int   TestAsOne0 (char   log)  {
        int   i;             
	unsigned   int   num=0,   val;             
	for (i=0;   i<8;   i++)    {                     
		val   =   log   >>   i;     Displaced                  
		Val   &=   0x01;     With 1 Phase                  
		if (val)                             
			num++;             
	}           

 	return   num;    
 }  


92. Write a function that receives a string that is a set of strings composed of hexadecimal numbers, which function to convert the set of strings received to decimal digits. and return the decimal number. "Reference Answer"
BOOL   Hextodec (   lpctstr   shex,int&   idec   )     {
         int   i,mid;        
	 int   len   =   lstrlen (   shex   );         
	if (   len>8   )             
		return   FALSE;         
	Mid   =   0;  
	 Idec   =   0;        
	 For (   i=0;i<len;i++   )     {            
		 if (   shex[i]>= ' 0 ' &&shex[i]<= ' 9 '   )                 
			Mid   =   shex[i]-' 0 ';             
		else   if (   shex[i]>= ' a ' &&shex[i]<= ' F '   )                 
			mid   =   Shex[i]   -' a '   +10;            
		 else   if (   shex[i]>= ' a ' &&shex[i]<= ' F '   )                
			 mid   =   Shex[i]   -' a '   +10;            
		 else                 
			return   FALSE;                 
		Mid   <<=   ((len-i-1) <<2);   The shift represents the N-th idec =idc+mid that becomes 2   ;        

	 return   TRUE;     
}  


93, enter a string, reverse it after the output.
"Reference Answer"
void Main () {  	
	char a[50];memset (a,0,sizeof (a));  	
	int i=0,j;  	
	Char T;  	
	Cin.getline (a,50, ' \ n ');  	
	For (I=0,j=strlen (a) -1;i<strlen (a)/2;i++,j--)  {  		
		t=a[i];  		
		A[I]=A[J];  		
		a[j]=t;  	
	}  	

	cout<<a<<endl;   
}


94, write an algorithm frequency, statistics in an input string each of the different characters appear frequency. Verify the algorithm with the appropriate test data.
"Reference Answer"
void frequency (string& s, char& a[], int& c[], int &k) 
{
	int i, j, len = S.length ();
	if (!len) {cout << "the string is empty." << Endl;  k = 0;  Return
	else 
	{  
		a[0] = s[0];  C[0] = 1;  k = 1;  	/* Statement S[i] is an overloaded operation of a string
   		/for (i = 1; i < Len; i++) C[i] = 0;  			/* Initialize
		/for (i = 1; i < Len; i++) 
		{/	 		* All characters in the detection string/
			j = 0;   while (J < K && A[j]!= s[i]) j + +; /* Check whether S[i] is in a[] 
			/if (j = = k) 
			{a[k] = s[i]; c[k]++; k++}		/*s[i] never detected * *
			else c[j]++;			/*S[I] has detected/}}}


95. Assume that the elements in the loop queue are stored in array q[m, with rear and length indicating the end position of the queue and the number of elements contained in the queues. Try to give the queue empty condition and the full team condition, and write out the appropriate insert (enqueue) and delete (Dlqueue) elements of the operation. "Reference answer" circular queue class definition
 #include <assert.h> template <class type> class Queue {//Loop queue definition Public:queue (int=10)
	;
	~queue () {delete [] elements}
	void EnQueue (Type & Item);
	Type dequeue ();
	Type Getfront ();		void Makeempty () {length = 0;}
Empty queue int IsEmpty () const {return length = = 0;}///isfull queue null no int () const {return length = = maxSize}//Queue full				Private:int rear, length;				Team tail pointer and queue Length Type *elements;				An array int maxSize that holds the queue element; The maximum number of elements the queue can hold}; 
Template <class type> queue<type>:: Queue (int sz): Rear (maxSize-1), Length (0), maxSize (SZ)   {//Establish a
An empty queue with a maximum of maxsize elements.		<span style= "White-space:pre" > </span>elements = new Type[maxsize];<span style= "White-space:pre" > </span>//Create queue space <span style= "White-space:pre" > </span>   assert (elements!= 0); <span style= " White-space:pre "> </span>//Assertion: Success of dynamic Storage allocation} Template<class type>  void queue<type>:: EnQueue (Type &item)   {<span style= "White-space:pre" > </span>assert (!) Isfull ()) <span style= "White-space:pre" > </span>//queue is dissatisfied, full error handling <span style= "White-space:pre" > &	Lt;/span>length++;<span style= "White-space:pre" > </span>//length plus 1 <span style= "White-space:pre" > </span>rear = (rear + 1)% Maxsize;<span style= "White-space:pre" > </span>//team Tail position into 1 <span style= "whit E-space:pre "> </span>elements[rear] = iteM;<span style= "White-space:pre" > </span>//into queue template<class type>  Type Queue<Type>:: Dequeue ()   {<span style= "White-space:pre" > </span>assert (! IsEmpty ()); <span style= "White-space:pre" > </span>//to determine whether the queue is not empty, empty error handling <span style= "White-space:pre" > </span >length--;<span style= "White-space:pre" > </span>//queue Length minus 1 <span style= "White-space:pre" > </ Span>return elements[(rear-length+maxsize)% Maxsize];<span style= "White-space:pre" > </span>// Returns the original team header element value} template<class type>  Type queue<type>:: Getfront ()   {<span style= "White-space:pre "> </span>assert (!)
IsEmpty ()); <span style= "White-space:pre" > </span>return elements[(rear-length+1+maxsize)% MaxSize];<span style=

 "White-space:pre" > </span>//return Team header element value}


96, known a[n] is an integer array, try to write a recursive algorithm to achieve the following operations:(1) to find the largest integer in array a.
(2) To find the number of n integers.
(3) To find the average of n integers.

"Reference Answer"
#include <iostream.h> class Recurvearray {//array class declaration Private:int *elements;		array pointer int arraysize;		Array dimensions int currentsize; Current number of array elements public:recurvearray (int MaxSize =10): ArraySize (MaxSize), Elements (new Int[maxsize]) {} ~ 
		Recurvearray () {delete [] Elements}		void Inputarray ();		Enter the contents of the array int maxkey (int n);		The maximum value int Sum (int n) is obtained.	To find the sum of the elements of the array float Average (int n);


To find the average value of an array element};
		void Recurvearray:: Inputarray () {//input array content cout << "input the number of array: \ n";
for (int i = 0; i < arraysize i++) cin >> Elements[i];
		int Recurvearray:: maxkey (int n) {//recursive maximum if (n = 1) return elements[0];
		int temp = Maxkey (n-1);
		if (elements[n-1] > Temp) return elements[n-1];
else return temp;
		int Recurvearray:: Sum (int n) {//recursive array and if (n = 1) return elements[0];
else return elements[n-1] + Sum (n-1); Float Recurvearray:: Average (int n) {///recursively evaluate the average of an array
		if (n = = 1) return (float) elements[0];
else return ((float) elements[n-1] + (n-1) * Average (n-1))/n;
			int main (int argc, char* argv []) {int size =-1; cout << "No.
			Of the Elements: ";
			while (Size < 1) cin >> size;
			Recurvearray ra (size); Ra.	
			Inputarray (); cout<< "\nthe max is:" << RA. Maxkey (RA.
			MaxSize) << Endl; cout<< "\nthe sum is:" << RA. Sum (RA.
			MaxSize) << Endl; cout<< "\nthe AVR is:" << RA. Average (RA.
			MaxSize) << Endl;
return 0;
 }



97, the known F is a single linked table of the table head pointer, the linked list is stored in the integer data, try to write the following operations to achieve the recursive algorithm:(1) to find the largest integer in the linked list.
(2) To find the number of nodes in the linked list.
(3) To find the average of all integers.

Answer

#include <iostream.h>//Definition of Class list in header file "RecurveList.h";			Class ListNode {//Link table node type friend class List; Private:int data;		Node data ListNode *link;
Node pointer listnode (const INT Item): Data (item), link (NULL) {}//constructor};
		Class List {//Linked list class Private:listnode *first, current;
		int Max (ListNode *f);
		int Num (ListNode *f);
Float AVG (ListNode *f, int& N); Public:list (): I (NULL), current (null) {}///constructor ~list () {}//destructor listnode* NewNode (const int ITE	m);	Creates a linked list node whose value is Item void newlist (const int retvalue);			Establish a linked list to enter the RetValue end void Printlist ();		Output list all node data int Getmax () {return Max (a)		To find the maximum value of all data in the list int getnum () {return Num (a)		Find the number of data in the list float Getavg () {return AVG.}	

To find the average of all the data in the linked list};
		listnode* List:: NewNode (const int Item) {//Create new linked list node ListNode *newnode = Newer listnode (item);
return newnode; } void List:: newlist (const int RetValue) {//Set up a linked list to enter RetvAlue end of the A = NULL;  int value;
		ListNode *q;		cout << "Input your data:\n";			Tips for cin >> value; Input while (value!= retvalue) {//input valid Q = NewNode (value);//Create a new node containing value if (A = NULL)  urrent = q;//Empty table, the new node becomes the first node of the list else {current->link = q; current = q;			}//Non-empty table, the new node links into the chain tail cin >> value;			Re-enter} Current->link = NULL;
		Chain End closed} void List:: Printlist () {//Output list cout << "\nthe List is: \ n";
		ListNode *p = A;  while (P!= NULL) {cout << p->data << '; 	p = p->link; 
} cout << ' \ n '; int List:: Max (ListNode *f) {//recursive algorithm: To find the maximum value if (f->link = = NULL) return f->data;//recursive end condition I		NT temp = Max (f->link);	Find the maximum if (F->data > Temp) return F->data; in the successor list of the current node.		If the value of the current node is still larger, return the current value of the order of the temp; Otherwise returns the maximum value in the successor list} int List:: Num (ListNode *f) {//recursive algorithm: Find the number of nodes in the list if (f = null) return 0;//Empty table, returns 0 return 1+ Num (f->link); Otherwise, returns the number of subsequent linked list nodes plus 1} float list:: Avg (ListNode *f, int& N) {//recursive algorithm: Find the average value of all elements in a linked list if (f->link = = N  ull)//list only one node, recursive end condition {n = 1; 
		return (float) (f->data);  else {Float Sum = AVG (f->link, N) * n;  n++; Return (f->data + Sum)/n;   }} #include "RecurveList.h"//defined in the main file int main (int argc, char* argv[]) {List test;
		int finished;
		cout << "Input table end sign data:";			Cin >> finished; Enter the build table end flag data test.		NewList (finished); Create a linked list test.			Printlist (); Print List cout << "\nthe Max is:" << test.
		Getmax (); cout << "\nthe Num is:" << test.
		Getnum (); cout << "\nthe Ave is:" << test.
		Getave () << ' \ n ';
		printf ("Hello world!\n");
return 0; }


98. Replacement of the string replace (string &s, String &t, String &v) means:If T is a substring of s, then a string v is substituted for all occurrences of the string T in the string s, and if T is not a substring of s, then the string s is unchanged. For example, if the string s is "Aabbabcbaabaaacbab", the string T is "Bab" and the string V is "ABDC", then the result in string S is "AABABDCCBAABAAACABDC" when the replace operation is performed. Try to use the basic operation of string to implement this substitution operation.
Reference answer
String & string:: Replace (String & T, string &v)
{ 	  
	if (int id = find (t)) = = 1) c3/>//not found, the current string does not change, return
	{cout << "the (replace) operation failed." << Endl;  return *this;   
	String Temp (ch);//Create an empty temporary string with the current string   
	ch[0] = ';  Curlen = 0;	The current string as the result string, initially null
  	int J, k = 0, L;		The pointer holding the result string while		 	 
	 (ID!=-1) {for 		 
		(j = 0; J < ID; j +) ch[k++] = temp.ch[j];	
		 Curlen + = id + v.curlen;		Modify the length of the result string connection
		 if (Curlen <= maxlen) L = V.curlen;//Determine the number of alternate string v transfer characters L
		 else {L = Curlen-maxlen;  Curlen = MaxLen; For
		 (j = 0; J < l; j +) ch[k++] = v.ch[j];
				The connection replaces the string V to the result string ch back
	 	 if (Curlen = = maxlen) break;	String out of range for
		 (j = id + T.curlen J < Temp.curlen J + +) 
			Temp.ch[j-id-t.curlen] = temp.ch[j];	The original string  	Temp.curlen-= (id + t.curlen) is deleted;
		id = temp. Find (t); 	  }
  		return *this;
} 



99. Try to write a function to solve Josephus problem. Using integer sequences 1, 2, 3, ..., n to indicate the order of people around the round table, and use array representation as the data structure used in the solution process. Then use n = 9, s = 1, M = 5, and n = 9, s = 1, m = 0, or n = 9, s = 1, m = 10 as input data, check the correctness and robustness of your program.
"Reference answer"
void Josephus (int a[], int n, S, m) {
	int i, j, K, TMP;
	if (M = = 0) {
		cout << "m = 0 is an invalid parameter. "<< Endl; 
		return;
	}
	for (i = 0; i < n; i++) A[i] = i + 1;		/* Initialize, execute n times *
	/i = s-1;				/* Registration Starting Position * *
	for (k = n; k > 1; i--) {/			* one out, execute n-1
		/if (i = = k) i = 0;
			i = (i + m-1)% K;		* * Look for the exit position *
		/if (i!= k-1) {
   			tmp = a[i];		* * The swap to the k-1 position * *
			(j = i; J < K-1; J +) A[j] = a[j+1];
			 A[K-1] = tmp;
		}
	}
		for (k = 0; k < N/2; k++) {/		* All inverses, get out sequence/
			TMP = A[k]; A[K] = a[n-k+1]; A[N-K+1] = tmp;
		}
	}



100. Constructors, destructors, and assignment functions that write class string are known to have a prototype of the class string:
Class string 
	 {public 
	   : 
	  string (const char *STR = NULL);//Normal constructor 
	  string (const string &other);     Copy constructor 
	  ~ String (void);         destructor 
	  string & operate = (const string &other);//Assignment Function 
	   private: 
	  char   *m_data;    Used to save the string 
	 }; 
Please write the above 4 functions of String. Answer
	The destructor of String string::~string (void) {delete [] m_data;
	 Since m_data is an internal data type, it can also be written as a delete m_data; 
	  }//String's normal constructor string::string (const char *str) {if (str==null) {    m_data = new Char[1];                       
	 If can add NULL judge is better *m_data = ' ";            
	  else {int length = strlen (str);      
	  m_data = new Char[length+1];                 
	 strcpy (m_data, str);   
	 }//Copy constructor string::string (const String &other) {int length = strlen (Other.m_data);      m_data = new Char[length+1];          
	It is better to judge the strcpy (m_data, other.m_data) If it can be added NULL. 
		}//Assignment function string & string::operate = (const string &other) {if (this = = &other) return *this; 
		delete [] m_data;  
		int length = strlen (Other.m_data);     
		m_data = new Char[length+1]; 
		strcpy (M_data, other.m_data); Return *this; 


 }













Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.