A few years ago, in response to the above questions, I would write the following code:
int i2a_old(int n, char *s) { char d,*e=s;//init begin pointer do{*e++='0'+n%10;}while(n/=10);//extract digits *e--=0;//set end of str_number int digits=es;//calc number of digits while(s<e)d=*s,*s++=*e,*e--=d;//reverse digits of the number return digits;//return number of digits }
I think the printf (...) function does something similar.
Now I will write the following:
int i2a_new(int n, char *s) { int digits=n<100000?n<100?n<10?1:2:n<1000?3:n<10000?4:5:n<10000000?n<1000000?6:7:n<100000000?8:n<1000000000?9:10; char *e=&s[digits];//init end pointer *e=0;//set end of str_number do{*--e='0'+n%10;}while(n/=10);//extract digits return digits;//return number of digits }
<strong> Advantages: search table separately; C, C ++, Java, JavaScript, compatible with PHP; get the number of digits, min comparisons: 3 ; get the number of digits, max comparisons: 4 ; fast code; the comparison is very simple and fast: cmp reg, immediate_data → 1 processor clock speed.
Ivan Gelov Sep 15 2018-11-11T00: 00Z
source share