1.利用棧的數據結構特點,將二進制轉換為十進制數
分析
由于棧具有先進后出的特性,我們輸入11001001的二進制數,出棧的順序就相反,將每個出棧的數帶入進制轉換公式得到的結果就是轉換之后的十進制數
完整代碼
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct {
ElemType * base;
ElemType * top;
int stackSize;
}sqStack;
/**
* 初始化
*/
void InitStack(sqStack * s){
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s->base)
exit(0);
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
/**
* 進棧
*/
void Push(sqStack * s, ElemType e){
if (s->top - s->base >= s->stackSize) { // 棧滿,擴大空間
s->base = (ElemType *)realloc(s->base, (s->stackSize * STACKINCREMENT) * sizeof(ElemType));
if (!s->base)
exit(0);
s->top = s->base + s->stackSize; // 設置棧頂
s->stackSize = s->stackSize + STACKINCREMENT; // 設置棧的最大容量
}
*(s->top) = e;
s->top++;
}
/**
* 出棧
*/
void Pop(sqStack * s, ElemType *e){
if (s->top == s->base) // 棧空
return;
s->top--; // 棧頂指針減1
*e = *(s->top); // 將要刪除的棧頂元素賦值給e
// *e = *--(s->top);
}
/**
* 獲取棧的當前容量
*/
int StackLen(sqStack s){
return (int)(s.top - s.base);
}
int main(int argc, const char * argv[]) {
ElemType e;
sqStack s;
int len,i,sum = 0;
// 初始化棧
InitStack(&s);
printf("請輸入二進制數,輸入#號表示結束!\n");
scanf("%c",&e);
while (e != '#') {
Push(&s, e);
scanf("%c", &e);
}
getchar(); // 把‘\n’從緩沖區去掉
len = StackLen(s);
printf("棧的當前容量是:%d\n", len);
for (i = 0; i < len; i++) {
Pop(&s, &e);
sum = sum + (e-48) * pow(2, i); // 這里是ASCII碼,所以要減去48
}
printf("轉化為十進制數是:%d\n", sum);
return 0;
}
輸出結果
二進制轉換為十進制