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

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

    The following prints the digits in order of ascending significance (i.e. units, then tens, etc.):

    do {
        int digit = n % 10;
        putchar('0' + digit);
        n /= 10;
    } while (n > 0);
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-11-27 05:00

    Integer version is trivial:

    int fiGetDigit(const int n, const int k)
    {//Get K-th Digit from a Number (zero-based index)
        switch(k)
        {
            case 0:return n%10;
            case 1:return n/10%10;
            case 2:return n/100%10;
            case 3:return n/1000%10;
            case 4:return n/10000%10;
            case 5:return n/100000%10;
            case 6:return n/1000000%10;
            case 7:return n/10000000%10;
            case 8:return n/100000000%10;
            case 9:return n/1000000000%10;
        }
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题