June 22, 2011

3 interview questions in 28 minutes

Filed under: Programming — Tags: , , , , — admin @ 7:36 pm

Hi,

I would like to share 3 interview questions which have been asked me during a job Interview.

1- Write a function which omits space characters and concatenates every word in a one string.
ex: “ABCD EF -GHI<" -> “ABCDEF-GHI<" 2- Write a function which calculates 1 digits in a uint8t variable. ex: 0xAA -> 4

3- Write a function which detects a linked list is singly circulated.

Here is the answers,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
 
typedef unsigned char uint8_t;
 
struct linked_list {
	int data;
	struct linked_list *next;
};
 
char string[] = "ABC DEF  -GHI    JKLM<";
uint8_t gdata = 0x55;
 
/*
*1- Write a function which omits space characters and concatenates every word in a one string.
*/
void omit_space_opt(char *ptr) 
{
    int shift = 0;
    do {
        if (*ptr ==' ') 
            shift++;
        else if (shift) 
            *(ptr-shift) = *ptr;
    } while (*ptr++);
}
 
/*
*2- Write a function which calculates 1 digits in a uint8t variable.
*/
uint8_t count_set_bits(uint8_t data) 
{
    uint8_t c = 0;
    while (data) {
        if (data & 1)
            c++;
        data >>= 1;
    }
    return c;
}
 
/* or more fancy one */
uint8_t count_set_bits_fancy(uint8_t data) 
{
    uint8_t c;
    for (c = 0; data; c++)
        data &= data - 1; 
    return c;
}
 
/*
*3- Write a function which detects a linked list is singly circulated.(*)
*/
int islistCircular(struct linked_list *head) {
 struct linked_list *ptr_slow   = head;
 struct linked_list *ptr_fast	= head;
 
 while (1) {
   if (ptr_slow && ptr_fast && ptr_fast->next) {
	ptr_slow = ptr_slow->next;
	ptr_fast = ptr_fast->next->next;
   } else {
	return 0;
   }
   if (ptr_slow == ptr_fast) {
      return 1;
   }
  }
}
 
int
main(int argc, char **argv) {
  printf("\n%s\n", string);
  omit_space(string);
  printf("\n%s\n", string);
  printf("\nbit numbers '1' in 0x%x is %d\n", gdata, count_set_bits(gdata));
  return 0;
}

* : you may read more detailed answer for this question from Expert C Programming, Peter Van Linden, Page 334, ISBN: 0-13-177429-8.

See you on another article…

Powered by WordPress