[Codewars] Compile time #3 itoa (number to string)

Compile time #3 itoa (number to string)

  • Time :
  • Space :
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
using namespace std;
constexpr char ord[] = "0123456789abcdefghijklmnopqrstuvwxyz";
using integer = unsigned long long;
template <integer X, integer Base = 10>
struct itoax {
static constexpr size_t digits() {
if (X == 0) return 1;
auto q = X;
size_t size = 0;
while (q > 0) {
q /= Base;
size++;
}
return size;
}
static constexpr auto value_array = []() constexpr {
std::array<char, digits() + 1> a{};
if (X == 0) {
a[0] = '0';
a[1] = '\0';
}
else {
auto q = X;
auto index = digits() - 1;
a[index] = '\0';
while (q > 0) {
a[index--] = ord[q % Base];
q /= Base;
}
}
return a;
}();
static constexpr const char* value = value_array.data();
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/08/PS/Codewars/compile-time-3-itoa/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.