计算十进制整数的子段组成的整数

#include <stdio.h>
#include <stdint.h>

const uint32_t powdec[10] = {
    1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000
};

uint32_t subNum(uint32_t number, uint8_t least, uint8_t most) {
    if (least == 0) {
        if (most == 9) {
            return number;
        } else {
            return number % powdec[most - least + 1];
        }
    } else {
        if (most == 9) {
            return number / powdec[least];
        } else {
            return (number / powdec[least]) % powdec[most - least + 1];
        }
    }
}

int main() {
    const uint32_t number = 1234567890;
    printf("%u\n", subNum(number, 0, 0));
    printf("%u\n", subNum(number, 1, 1));
    printf("%u\n", subNum(number, 0, 2));
    printf("%u\n", subNum(number, 1, 3));
    printf("%u\n", subNum(number, 0, 9));
    printf("%u\n", subNum(number, 1, 9));
    printf("%u\n", subNum(number, 7, 8));
    printf("%u\n", subNum(number, 8, 8));
    printf("%u\n", subNum(number, 8, 9));
    printf("%u\n", subNum(number, 9, 9));
    return 0;
}


你可能感兴趣的:(计算十进制整数的子段组成的整数)