Exercise 3-6
Enter cardinality B (2<=b<=10) and positive integer n (decimal), and the B-binary representation of the output n.
#include <stdio.h> #include <stdlib.h> #define MAXN 100int a[maxn];int Main (int argc, char *argv[]) { int b , n, i = 0, J; scanf ("%d%d", &b, &n); while (n/b! = 0 | | n%b! = 0) { a[i++] = n%b; n = n/b; } for (j = i-1; J >= 0; j--) printf ("%d", a[j]); printf ("\ n"); System ("PAUSE"); return 0;}
Summary: N>0 can be used as a condition for judging
Exercise 3-7
Enter cardinality B (2<=b<=10) and positive integer n (b-binary), and the decimal representation of the output n.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define MAXN 100char a[maxn];int Main (int argc, char *argv[]) { int b, Length, I, J; int n = 0; scanf ("%d", &b); scanf ("%s", a); Length = strlen (a); for (i = length-1, j = 0; I >= 0; I--, j + +) { n = n + (a[i]-' 0 ') *pow (b,j); } printf ("%d\n", n); System ("PAUSE"); return 0;}
Algorithmic competition Getting Started classic exercise 3-5 3-6 binary conversion