1049. Counting Ones (30)解题报告

#define _CRT_SECURE_NO_WARNINGS

#include 
#include 
#include 
#include 
using namespace std;

int main(void) {
    long long matrix[12][10] = { {0} };
    long long i, j, base, sum, n;
    for (i = 1; i < 10; i++) {
        matrix[0][i] = 1;
    }
    base = 10;
    for (i = 1; i < 12; i++) {
        sum = matrix[i - 1][9] + matrix[i - 1][1] - 1;
        matrix[i][1] = sum + 1;
        matrix[i][2] = base + sum * 2;
        base *= 10;
        for (j = 3; j < 10; j++) {
            matrix[i][j] = matrix[i][1] + matrix[i][j - 1] - 1;
        }
    }

    scanf("%lld", &n);
    stack<int> s;
    int tmp = n;
    while (tmp > 0) {
        s.push(tmp % 10);
        tmp /= 10;
    }
    tmp = n;
    sum = 0;
    base = 1;
    while (tmp > 0) {
        base *= 10;
        tmp /= 10;
    }
    tmp = n;
    base /= 10;
    while (!s.empty()) {
        i = s.size() - 1;
        j = s.top();
        s.pop();
        sum += matrix[i][j];
        if (j == 1) {
            sum += tmp % base;
        }
        tmp %= base;
        base /= 10;
    }
    printf("%lld\n", sum);
    return 0;
}

你可能感兴趣的:(PAT)