-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfacebook_int_to_str.txt
94 lines (71 loc) · 1.83 KB
/
facebook_int_to_str.txt
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
// Fast Convert Int to String
// https://www.facebook.com/notes/10158791579037200/
// Online C compiler to run C program online
#include <stdio.h>
#define P01 10
#define P02 100
#define P03 1000
#define P04 10000
#define P05 100000
#define P06 1000000
#define P07 10000000
#define P08 100000000
#define P09 1000000000
#define P10 10000000000
#define P11 100000000000
#define P12 1000000000000
int digits10(int v) {
if (v < P01) return 1;
if (v < P02) return 2;
if (v < P03) return 3;
if (v < P12) {
if (v < P08) {
if (v < P06) {
if (v < P04) return 4;
return 5 + (v >= P05);
}
return 7 + (v >= P07);
}
if (v < P10) {
return 9 + (v >= P09);
}
return 11 + (v >= P11);
}
return 12 + digits10(v / P12);
}
unsigned u64ToAsciiTable(int value, char* dst) {
static const char digits[201] =
"0001020304050607080910111213141516171819"
"2021222324252627282930313233343536373839"
"4041424344454647484950515253545556575859"
"6061626364656667686970717273747576777879"
"8081828384858687888990919293949596979899";
int const length = digits10(value);
int next = length - 1;
while (value >= 100) {
auto const i = (value % 100) * 2;
value /= 100;
dst[next] = digits[i + 1];
dst[next - 1] = digits[i];
next -= 2;
}
// Handle last 1-2 digits
if (value < 10) {
dst[next] = '0' + value;
} else {
auto i = value * 2;
dst[next] = digits[i + 1];
dst[next - 1] = digits[i];
}
dst[length]='\0';
return length;
}
int main() {
// Write C code here
printf("Hello world\n");
char *num_str[100];
int num = 12345;
u64ToAsciiTable(num, num_str);
printf("num=[%d], str=[%s]\n", num, num_str);
return 0;
}