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

前端 未结 15 1283
既然无缘
既然无缘 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:59

    Get all the individual digits into something like an array - two variants:

    int i2array_BigEndian(int n, char a[11])
    {//storing the most significant digit first
        int digits=//obtain the number of digits with 3 or 4 comparisons
        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;
        a+=digits;//init end pointer
        do{*--a=n%10;}while(n/=10);//extract digits
        return digits;//return number of digits
    }
    
    int i2array_LittleEndian(int n, char a[11])
    {//storing the least significant digit first
        char *p=&a[0];//init running pointer
        do{*p++=n%10;}while(n/=10);//extract digits
        return p-a;//return number of digits
    }
    

提交回复
热议问题