当前位置:网站首页>利用棧來實現二進制轉化為十進制

利用棧來實現二進制轉化為十進制

2022-07-07 12:26:00 舍不得,放不下

如何實現二進制轉化為十進制呢?

舉個栗子吧:比如(100101)2(這個2是下標哈)轉化為十進制的方法:

1*2^0+0*2^1+1*2^2+0*2^3+0*2^4+1*2^5

知道這個接下來就好辦了:100101入棧順序1->0->0->1->0->1

廢話不多數,直接上代碼

先用結構體定義一個棧:

typedef struct {
	ElemType *base;
	ElemType *top;
	int stacksize;
} sqstack;

初始化棧:

void InitStack(sqstack *s) { //初始化棧
	s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType)); //malloc申請空間,
	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));//realloc申請空間,將原有數據保存,並添加新的空間,來找新的一份空間儲存數據
	 
		if (!s->base) {
			exit(0);
		}
	}
	*(s->top) = e;//棧頂賦值 
	s->top++;//棧頂+1 
}

拋出(出棧)操作:

void Pop(sqstack*s, ElemType*e) {//拋出操作 
	if (s->top == s->base) {
		return;
	}
	*e = *--(s->top); 
}

計算棧的長度:

int StackLen(sqstack s) {//計算棧的長度 
	return (s.top - s.base);
}

主函數:

int main() {
	ElemType c;
	sqstack s;
	int len, sum = 0;
	InitStack(&s);
	printf("請輸入二進制數,輸入#符號錶示結束!\n");
	scanf("%c", &c);
	while (c != '#') {
			Push(&s, c);
			scanf("%c", &c);
		}
	getchar();//吸收空格 
	len = StackLen(s);
	printf("棧的當前容量是:%d\n", len);
	for (int i = 0; i < len; i++) {
		Pop(&s, &c);
		sum = sum + ((c - 48) << i);//c-48由ascll碼錶轉化為整形,(c-48)<<i比特運算相當於2^i 
	}
	printf("轉化的十進制數是:%d\n", sum);
	return 0;
}

整個代碼:

#include<stdio.h>
#include<stdlib.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)); //malloc申請空間,
	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));//realloc申請空間,將原有數據保存,並添加新的空間,來找新的一份空間儲存數據
	 
		if (!s->base) {
			exit(0);
		}
	}
	*(s->top) = e;//棧頂賦值 
	s->top++;//棧頂+1 
}
void Pop(sqstack*s, ElemType*e) {//拋出操作 
	if (s->top == s->base) {
		return;
	}
	*e = *--(s->top); 
}
int StackLen(sqstack s) {//計算棧的長度 
	return (s.top - s.base);
}
int main() {
	ElemType c;
	sqstack s;
	int len, sum = 0;
	InitStack(&s);
	printf("請輸入二進制數,輸入#符號錶示結束!\n");
	scanf("%c", &c);
	while (c != '#') {
			Push(&s, c);
			scanf("%c", &c);
		}
	getchar();//吸收空格 
	len = StackLen(s);
	printf("棧的當前容量是:%d\n", len);
	for (int i = 0; i < len; i++) {
		Pop(&s, &c);
		sum = sum + ((c - 48) << i);//c-48由ascll碼錶轉化為整形,(c-48)<<i比特運算相當於2^i 
	}
	printf("轉化的十進制數是:%d\n", sum);
	return 0;
}

原网站

版权声明
本文为[舍不得,放不下]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071027393654.html