-
Notifications
You must be signed in to change notification settings - Fork 1
/
Itoa.c
53 lines (43 loc) · 985 Bytes
/
Itoa.c
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
#include <iostream>
using namespace std;
void reverse(char str[], int length) {
int start = 0;
int end = length - 1;
while (start < end) {
swap(*(str + start), *(str + end));
start++;
end--;
}
}
char *itoa(int num, char *str, int base) {
int i = 0;
bool isNegative = false;
if (num == 0) {
str[i++] = '0';
str[i] = '\0';
return str;
}
if (num < 0 && base == 10) {
isNegative = true;
num = -num;
}
while (num != 0) {
int rem = num % base;
str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
num = num / base;
}
if (isNegative)
str[i++] = '-';
str[i] = '\0';
reverse(str, i);
return str;
}
int main() {
char str[100];
cout << "Base:10 " << itoa(1567, str, 10) << endl;
cout << "Base:10 " << itoa(-1567, str, 10) << endl;
cout << "Base:2 " << itoa(1567, str, 2) << endl;
cout << "Base:8 " << itoa(1567, str, 8) << endl;
cout << "Base:16 " << itoa(1567, str, 16) << endl;
return 0;
}