-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfast_to_string.cpp
36 lines (31 loc) · 1023 Bytes
/
fast_to_string.cpp
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
#include <string>
#include <iostream>
#include <limits>
#include <type_traits>
#include <cstdlib>
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
std::string to_string(T i) {
constexpr int max = std::numeric_limits<T>::digits10 + 2;
char buffer[max]={};
int start=max;
bool negative=i<0;
do {
T q = i/10;
T r = i%10;
buffer[--start] = static_cast<char>('0'+(negative ? -r : r));
i = q;
} while (i);
if (negative)
buffer[--start]='-';
return {&buffer[start], &buffer[max]};
}
int main() {
std::cout <<to_string(std::numeric_limits<int>::min()) <<std::endl;
std::cout <<std::numeric_limits<int>::min() <<std::endl;
std::cout <<std::numeric_limits<char>::digits10 <<'\n';
std::cout <<std::numeric_limits<short>::digits10 <<'\n';
std::cout <<std::numeric_limits<int>::digits10 <<'\n';
std::cout <<std::numeric_limits<long>::digits10 <<'\n';
std::cout <<std::numeric_limits<long long>::digits10 <<'\n';
return 0;
}