How to get the digits of a number without converting it to a string/ char array?

前端 未结 15 1258
既然无缘
既然无缘 2020-11-27 04:07

How do I get what the digits of a number are in C++ without converting it to strings or character arrays?

15条回答
  •  难免孤独
    2020-11-27 04:33

    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=e-s;//calc number of digits
        while(s

    I think that the function printf(...) does something like that.

    Now I will write this:

    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
    }
    

    Advantages: lookup table indipendent; C,C++,Java,JavaScript,PHP compatible; get number of digits, min comparisons: 3; get number of digits, max comparisons: 4; fast code; a comparison is very simple and fast: cmp reg, immediate_data --> 1 CPU clock.

提交回复
热议问题