forked from raviswan/ProgrammingProblems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquare_interview.c
More file actions
108 lines (89 loc) Β· 1.75 KB
/
Square_interview.c
File metadata and controls
108 lines (89 loc) Β· 1.75 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
// https://en.wikipedia.org/wiki/Stdarg.h
// http://www.cplusplus.com/reference/cstdarg/
/*Implementing itoa*/
char* sq_itoa(int a){
char* c = malloc(sizeof(char)*256);
char temp;
size_t i =0;
size_t j;
size_t len = 0;
while(a!=0){
c[i] = a%10+'0';
a = a/10;
i++;
len++;
}
j= len-1;
i=0;
while(i<=j){
temp = c[i];
c[i]=c[j];
c[j]=temp;
i++;
j--;
}
c[len] = '\0';
return c;
}
/*implementing atoi*/
int sq_atoi(char* a){
int res = 0;
while(*a != '\0'){
res = 10*res + *a-'0';
a++;
}
return res;
}
int sq_sprintf(char *buf, char const *fmt, ...)
{
//char* fmtPtr;
va_list vl;
va_start(vl,fmt);
int param;
char* str;
if (fmt == NULL) {
return -1;
}
while(*fmt != '\0'){
if(*fmt=='%'){
fmt++;
if(*fmt=='d'){
param = va_arg(vl,int);
str = sq_itoa(param);
printf("val=%d ,str=%s\n",param,str);
memcpy(buf,str,strlen(str));
buf += strlen(str);
fmt++;
}
else if(*fmt=='s'){
str = va_arg(vl,char*);
memcpy(buf,str,strlen(str));
buf += strlen(str);
fmt++;
}
}
else{
*buf++ = *fmt++;
}
}
*buf = '\0';
return 0;
}
int main() {
int i=13433;
char buf[100];
char* str = sq_itoa(i);
printf("itoa: %s\n", str);
free(str);
sq_sprintf(buf, "This is a test case ");
printf("%s\n", buf);
sq_sprintf(buf, "This is a test case with a %s", "string");
printf("%s\n", buf);
sq_sprintf(buf, "This is %s %s with %d", "test", "case",i);
printf("%s\n", buf);
return 0;
}