数据结构之(HDU2051 Bitset)
Problem Description
Give you a number on base ten,you should output it on base two.(0 < n < 1000)
Input
For each case there is a postive number n on base ten, end of file.
Output
For each case output a number on base two.
Sample Input
1
2
3
Sample Output
1
10
11
1.普通方法
代码如下:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 int main() 6 { 7 int a[100]; 8 int n; 9 int m; 10 int i; 11 while(cin>>n) 12 { 13 i=0; 14 while(n) 15 { 16 i=i+1; 17 a[i]=n%2; 18 n/=2; 19 } 20 for(i;i>0;i--) 21 cout<<a[i]; 22 cout<<endl; 23 } 24 return 0; 25 }
运用桟解决:
代码如下:
1 #include "stdafx.h" 2 #include<iostream> 3 #include<cstdlib> 4 using namespace std; 5 #define OK 1 6 #define ERROR 0 7 #define OVERFLOW -2 8 #define MAXSIZE 100 9 typedef int Status; 10 typedef int SElemType; 11 12 typedef struct 13 { 14 SElemType *base; 15 SElemType *top; 16 int stacksize; 17 }SqStack; 18 19 Status InitStack(SqStack &S) //桟的初始化 20 { 21 S.base = new SElemType[MAXSIZE]; 22 if (!S.base) 23 exit(OVERFLOW); 24 S.top = S.base; 25 S.stacksize = MAXSIZE; 26 return OK; 27 } 28 29 Status Push(SqStack &S, SElemType e) //进栈 30 { 31 if (S.top - S.base == S.stacksize) 32 return ERROR; 33 *S.top++ = e; 34 return OK; 35 } 36 37 Status Pop(SqStack &S, SElemType &e) //出桟 38 { 39 if (S.top == S.base) 40 return ERROR; 41 e = *--S.top; 42 return OK; 43 } 44 int main() 45 { 46 int N; 47 SqStack S; 48 SElemType e; 49 InitStack(S); 50 while (cin >> N) 51 { 52 while (N != 0) 53 { 54 e = N % 2; 55 Push(S, e); 56 N = N / 2; 57 } 58 while (!(S.top == S.base)) 59 { 60 Pop(S, e); 61 cout << e; 62 } 63 cout << endl; 64 } 65 return 0; 66 }