How to extract digits from a number in C? Begining from the most significant digit?

后端 未结 6 954
无人及你
无人及你 2020-12-18 12:25

Getting digits from a number beginning from the least significant in C is pretty easy:

#include 

int main()
{
    int num = 1024;

    while(         


        
6条回答
  •  离开以前
    2020-12-18 12:41

    Here is my try. Works for positive numbers only. Max range 2^64 (unsigned long long)

    #include 
    #include 
    
    using namespace std;
    using bignum = unsigned long long;
    
    inline
    bignum Power(unsigned x, unsigned y) {
        return y>0 ? x*Power(x,y-1) : 1;
    }
    
    // return digits count in a number
    inline
    int Numlen(bignum num) {
        return num<10 ? 1 : floor(log10(num))+1;
    }
    
    // get the starting divisor for our calculation
    inline
    bignum Getdivisor(unsigned factor) {
        return Power(10, factor);
    }
    
    
    int main()
    {
        bignum num{3252198};
        //cin >> num;
    
        unsigned numdigits = Numlen(num);    
        auto divisor = Getdivisor(numdigits-1);
    
        while(num > 0) {
    
            cout << "digit = " << (num/divisor) << "\n";
    
            num %= divisor;
            divisor /= 10;
        }
    }
    
    /*
    output:
    digit = 3
    digit = 2
    digit = 5
    digit = 2
    digit = 1
    digit = 9
    digit = 8
    */
    

提交回复
热议问题