PAT 1049 Counting Ones
#include <cstdio> #include <cstdlib> using namespace std; #define COL 10 #define ROW 10 int tbl[ROW][COL]; void print(int* tbl) { for (int i=0; i<ROW; i++) { for (int j=0; j<COL; j++) { printf("%11d", tbl[i * COL + j]); } printf("\n"); } } int ones_aux(int num, int digits, int tens) { if (digits < 1 || tens < 1) return 0; int first = num / tens; int sum = 0; for (int i=0; i<first; i++) { sum += tbl[digits-1][i]; } if (first == 1) { sum += num % tens + 1; } int subsum = ones_aux(num % tens, digits - 1, tens / 10); return sum + subsum; } int ones(int num) { int digits = 1; int tmp = num; int tens = 1; while (tmp) { tmp /= 10; if (tmp) { tens *= 10; digits++; } } return ones_aux(num, digits, tens); } int main() { int tens = 1; int sum = 0; for (int i=0; i<ROW; i++) { for (int j=0; j<COL; j++) { if (j == 0) { tbl[i][j] = sum; continue; } if (j == 1) { tbl[i][j] = tens * 1; } tbl[i][j] += tbl[i][0]; sum += tbl[i][j]; } tens *=10; } int n; scanf("%d", &n); printf("%d\n", ones(n)); system("pause"); return 0; }
0 1 0 0 0 0 0 0 0 0 1 11 1 1 1 1 1 1 1 1 20 120 20 20 20 20 20 20 20 20 300 1300 300 300 300 300 300 300 300 300 4000 14000 4000 4000 4000 4000 4000 4000 4000 4000 50000 150000 50000 50000 50000 50000 50000 50000 50000 50000 600000 1600000 600000 600000 600000 600000 600000 600000 600000 600000 7000000 17000000 7000000 7000000 7000000 7000000 7000000 7000000 7000000 7000000 80000000 180000000 80000000 80000000 80000000 80000000 80000000 80000000 80000000 80000000 900000000 1900000000 900000000 900000000 900000000 900000000 900000000 900000000 900000000 900000000
先生成0~9, x0~x9, x00~x99, x000~x999...这这些范围内的1数量表,然后把输入的数组一步一步拆分到这些区域上如321 = 00~099 + 100~199 + 200~299 + 00~09 + 10~19 + 0~1,当然对于开头为1的数字需要额外加上一些