#include "stdio.h" #include "string.h" char res1[512]; char res2[512]; void calc(int n) { int i, k, a, b; if (n < 8) { k = sprintf(res1, "%s", "1"); for (i = 2; i <= n; i++) k += sprintf(&res1[k], "%s", "+1"); } else { k = 0; for (i = 0; i <=30; i++) if (((n >> i) & 1) != 0) k = i; k--; a = 0; for (i = k; i >= 0; i--) { b = (n >> i) & 1; if (i == k) { if (a == 0) sprintf(res2, "%s", "(1+1)"); else sprintf(res2, "%s", "(1+1)+1"); } else { if (a == 0) sprintf(res2, "(1+1)*%s", res1); else sprintf(res2, "(1+1)*(%s)", res1); } if (b == 0) sprintf(res1, "%s", res2); else sprintf(res1, "%s+1", res2); a = b; } } printf("%s\n", res1); } int main() { int t; int n; scanf("%d", &t); while (t--) { scanf("%d", &n); calc(n); } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | #include "stdio.h" #include "string.h" char res1[512]; char res2[512]; void calc(int n) { int i, k, a, b; if (n < 8) { k = sprintf(res1, "%s", "1"); for (i = 2; i <= n; i++) k += sprintf(&res1[k], "%s", "+1"); } else { k = 0; for (i = 0; i <=30; i++) if (((n >> i) & 1) != 0) k = i; k--; a = 0; for (i = k; i >= 0; i--) { b = (n >> i) & 1; if (i == k) { if (a == 0) sprintf(res2, "%s", "(1+1)"); else sprintf(res2, "%s", "(1+1)+1"); } else { if (a == 0) sprintf(res2, "(1+1)*%s", res1); else sprintf(res2, "(1+1)*(%s)", res1); } if (b == 0) sprintf(res1, "%s", res2); else sprintf(res1, "%s+1", res2); a = b; } } printf("%s\n", res1); } int main() { int t; int n; scanf("%d", &t); while (t--) { scanf("%d", &n); calc(n); } return 0; } |