The most often asked in the interview, Algorithms & Coding

xiaoxiao2021-03-06  98

Algorithms & Coding Questions & Answers

1, Write a Function to Print The Fibonacci Numbers.

- INT FIB (INT N) {IF (n == 0) Return 1; Else Return FIB (N-1) FIB (N-2);}

- int fibo (int N) {INT I, CURRENT, One_BACK, TWO_BACK;

IF (n <= 1) Return 1; else {one_back = 1; two_back = 1; for (i = 2; i <= n; i ) {current = one_back two_back; one_back = two_back; two_back = current;} / * End for loop * /} / * end else block * / return current;

- There are better ways to find a solution to this problem instead of using Recursion Recursion is a disaster as someone has already mentioned Try giving 20 or more elements in your series and your program will take awful lot of time to compute For... Every Element In Series You're Finding The Element Before Using Recursion Though You Theoretical You Would Have Comput IT Before !!!

2. Give a One-Line C Expression to Test WHETHER A Number IS A Power of 2. NOW IMPLEMENT ITWITHOUT Using Loops.

- IF (x> 0 && (x & (x-1)) == 0)

- I Think All The Answers Here Are Either Wrong Completely, Partially, or Too Complex. The Best Answer So Far, by Jinjhaveri, Was IF (! (X & (x-1))), Which I Believe Works for All Powers of 2, But Also for 0, Which is not a power of 2.

Basically, an integer which is the power of 2 Will Have One And Only One Bit Set in Its Binary Representation. If You Subtract 1 from That, You Will Get All Bits Set (Equal to 1) Before The Original 1 Bit, And The Rest Are 0. Taking Advantage Of this, The Answer IS

IF ((x << 1) == 1 (x | (x - 1))) {}

The Term x | (x - 1) Makes an INTEGER WITH BITS STT Starting from the Original Set Bit Bit And Clear All The Previous Bits, Effectively Doubling X, Which Is The Same As x << 1 .It's a pity what the second solutions work for 0 Too, Which is Just What HE / She Wants To Avoid.

3. Implement an algorithm to sort a linked list.

Directly insert sort, select sort, and sort it.

If the additional memory space can be used, it will be more simple; otherwise, you need a little thoughts.

4. REVERSE A STRING.

Void str_rev (char s []) {int LEN = Strlen (s); int 1; char Temp; for (i = 0; i

{TEMP = S [i]; s [i] = s [(len-1) - I]; s [(len-1) - i] = TEMP;}}

5. Given a Linked List Which is sorted, how will you insert in sorted Way.

U Have Already Very Familiar with it if you div Question 3 (Sort a Linked List) by Direct Insertion Sort.

6. Implement an algorithm to insert in a sorted list.

7. Delete An Element from a Doubly Linked List.

Void deletenode (node ​​* n) {node * np = n-> prev; node * nn = n-> next; np-> next = n-> next; nn-> prev = n-> prev; delete n;

8. Implement an algorithm to sort an arch.

An Array Can Be Sorted Using Any of The Classic Algorithms Like Quicksort, Heapsort and the inefficient bubblesort.

9. Given a Sequence of Characters, How Will You Convert The Lower Case Characters to Upper Case Characters?

Void Toupper (CHAR * S) {While (* S! = 0) {* s = (* s> = 'a' && * s <= 'z')? (* s-'a ' ' a ') : * S; s ;}}

10. Write a Routine That Prints Out A 2-D Array In Spiral ORDER.

INT number; // around the edge of the circle

INT TINIT = 0; // The starting value of the winding

For (int i = 0; i <(size 1) / 2; i ) {

Int t = Tinit;

For (int J = 0; J

{

// out here

PrintData (T);

T = Size;

}

For (j = 0; j

{

// out here

PrintData (T);

T = 1;

}

For (j = 0; j

{

// out here

PrintData (T);

T - = size;

}

For (j = 0; j

{

// out here

PrintData (T);

T - = 1;

}

NumBerspertime - = 2;

Tinit = Size 1;

}

11. Give a fast way to multiply a number by 7.

INT NUM = (n << 3) - N;

12. Write a Function That Takes in a string parameter and checks to see the integer, and if it is the the rete the integer value.

INT str2int (const char * str) {int value = 0; int Sign = (STR [0] == '-')? - 1: 1; INT I = (STR [0] == '-')? 1 : 0; char ch; While (CH = STR [i ])

{IF ((CH> = '0') && (CH <= '9')) Value = Value * 10 (CH - '0'); Elsereturn 0; // Return 0 DENOTES ERROR OCCURS} Return Value * SIGN }

13. How Would You Print Out The Data I Binary Tree, Level By Level, Starting At the top?

1) Put the root node in queue; 2) While the queue is not empty, do as follows; 3) get a node from the queue, print its value

14. Write a Routine to Draw A Circle Given a Center Coordinate (X, Y) And A Radius (r) without Making Use of any floating point computations.

In Order to Avoid Floating Point Calculation, We can do two things:

1) Instead of Fixing One Co-Ordinate and Looking For Another Via The Equation, Search The Whole Co-Ordinate Space from X - R and Y - R. Plot The Point That Is Close. But this is a costly n * n Algo.2) To Go for An Efficient Workhorse, Go for Bresenham's Circle Drawing Algo, Found In any of the good graphics textbooks.15. You are Given Two Strings: S1 and S2. Delete from S2 All Those Characters Which Occur in S1 Also and create a Clean S2 with the release character characters deled.

#include #include main () {char str1 [5] = "abcd"; char str2 [3] = "bc"; int LEN = Strlen (str1); int i = 0 CHAR newsTR [LEN]; int CNTR = 0; for (i = 0; I

16. Write a Small Lexical Analyzer for Expressions Like "A * B" ETC.

BOOL IS_ASTARB (CHAR * S) {IF (* S ! = 'a') Return False; While (* S ); if (* - s! = 'b') Return False; Return True;}

17. Given an array t [100] Which contains number between 1 and 99. Return the duplicated value. Try both o (n) and o (n-square).

- Traverse Array To Compute SUM, SUBTRACT 99 * 100/2, The Sum of Integers Between 1 and 99.

- Create a New Array of B [100], Elements Initialized all to 0

INT B [100]; for (i = 0; I <100; I ) B [i] = 0; int Tm; for (i = 0; i <100; i ) {TM = T [i]; if b [TM] == 1; Return (TM); // Return The duplicate Numberelse B [TM] = 1;} PRINTF ("" there is no duplication "); return 0; // 0 INDICES NO DUPLICATION

O (n square) ... Just Sort All Numbers and check if two consecutive numbers are same by traversing the sorted array..18. Write Efficient Code for Extracting Unique Elements from a sorted list of arrrey.

#include

Main () {Int a [10] = {0, 4, 4, 4, 5, 6, 6, 8, 9, 9}; int I;

For (i = 0; i <10; i ) {if (a [i] == a [i 1]) {while (a [i] == a [i 1]) i ;} elseprintf (" % D ", A [I]);} Printf (" / n ");

We do Print The Ununique Numbers out, But we do not extract the!

19. Print An Integer Using Only Putchar. Try Doing It WITHOUT Using Extra Storage.

1) Void Printint (INT A; CHAR * STR; INT i = 1; int Len = 0; while (b) {b / = 10; i * = 10; len ;} I / = 10 ;

While (I> 0) {PUTCHAR (A / I 48); A = a% I; I / = 10;}}

2) This Can Be Done by Recursion. Since The Number of Recursive Calls IS Not Significant, IT Does Not Affect The Performance Much.

PrintNumber (INT I) {IF (i == 0) Return; PrintNumber (I / 10); PUTCHAR ('0' I% 10);}

20. Write a Function That Allocates Memory for A Two-Dimensional Array of Given Size (Parameter X & Y)

--Array = (int **) Malloc (= 0; i

--I prefer this method because it uses less memory allocation calls and the memory is in a contiguous line. I used calloc .. which can easily be swaped out with malloc. Also, this makes a 2d array of integers but that is easily changed AS Well.

INT x = 0, y = 0; array = (int **) Calloc (Height, SIZEOF (INT *)); * (array) = (int *) Calloc (Width * Height, Sizeof (int));

FOR (Y = 0; Y

# neydef / ifndef # else / Elif # ENDIF

#pragma token-string // provide compiler or machine specific instructions and arguments

twenty two. WRITE AN Algorithm to Draw A 3D PIE CHART?

twenty three. Write a Function That Finds REPEATING Characters in A String.

Maintain a character count Table Like - Int char_count [255];

// Initialize to 0 here Keep Adding The Count of Each Characters.scan Throughout The Array and Print The Characters with Count More Than 1.

twenty four. Write a Routine to Reverse A Series of Numbers without using an arrrey.

- int Reverse (INT I) {int REV = 0, x = 0; IF ((i / 10) == 0) Return I; While ((I / 10)> 0) {x = I% 10; I = I / 10; REV = (REV * 10) x;} REV = Rev * 10 i; return rev;}

- # include void main () {INT i = 12345, y = 0; while (i! = 0) {y = y * 10 i% 10; I / = 10;} cout << Y;}

25. Write a Function to Find The Nth Item from the end of a linked list in a single pass.

I would do...

26. Write a Function to Compute The Factorial of a Given Integer.

27. Give me an algorithm for telling me the number I Didn't Give You in a Given Range of Numbers (NumBers Are Given At Random)

1. SAY THE RANGE OF NUMBERS IS 0 To N-12. Initialize An Array Say, Seen [N] to 03. for Every Number I Given Set Seen [i] to 1.4. In the end, print all indices for which seen [ Index] = 0

28. Write a Function That Finds The Last Instance of a Character in A String.main () {

Char * x = "acbcd";

CHAR Y = 'c';

INT LEN = Strlen (x);

INT i = 0, J = 0;

For (i = len-1; i> = 0; I -) {

IF (x [i] == y) {

Break;

}

}

Printf ("% S% C% S% S% D% S", "the # of last occur of", y, "IS", i 1, "/ n");

}

转载请注明原文地址:https://www.9cbs.com/read-97730.html

New Post(0)