網站首頁 編程語言 正文
問題描述
利用棧的數據結構實現將十進制數轉換成二進制數
C語言實現
順序表的存儲結構實現棧
代碼:
#include <stdlib.h>
#include <stdio.h>
#define STACK_INIT_SIZE 100 //棧初始開辟空間大小
#define STACK_INCREMENT 10 //棧追加空間大小
//棧的結構體
typedef struct stack{
int *base;
int *top;
int size;
}binStack;
//棧初始化
binStack stack_init()
{
binStack bs;
bs.base = (int *)malloc(sizeof(int)*STACK_INIT_SIZE);
bs.top = bs.base;
bs.size = STACK_INIT_SIZE;
return bs;
}
//入棧
void push(binStack *bs, int e)
{
if(bs->top - bs->base >= bs->size)
{
bs->size += STACK_INCREMENT;
bs->base = realloc(bs->base, bs->size);
}
*(bs->top++) = e;
}
//出棧
int pop(binStack *bs)
{
if(bs->top != bs->base)
{
bs->top--;
return *bs->top;
}
return -1;
}
//主函數
void main()
{
int dec;
binStack bs = stack_init();
printf("請輸入十進制整數:\n");
scanf("%d", &dec);
while(dec)
{
push(&bs, dec%2);
dec /= 2;
}
printf("轉換后的二進制數是:\n");
while(bs.top != bs.base)
{
printf("%d", pop(&bs));
}
printf("\n\n");
system("date /T");
system("TIME /T");
system("pause");
exit(0);
}
運行結果:
Python實現
對于stack我們可以使用python內置的list實現(也可以用鏈表實現),因為list是屬于線性數組,在末尾插入和刪除一個元素所使用的時間都是O(1),這非常符合stack的要求。
代碼:
import datetime //顯示時間引入的庫
import time //
from pip._vendor.distlib.compat import raw_input //使命令窗口不立即關閉引入的庫
//棧類
class BinStack:
def __init__(self):
self.bs = []
//入棧
def push(self, e):
self.bs.append(e)
//出棧
def pop(self):
if self.bs:
return self.bs.pop()
else:
raise LookupError("stack is empty!")
//檢查棧是否為空,是返回False,不是返回True
def isEmpty(self):
return bool(self.bs)
if __name__ == '__main__':
binStack = BinStack()
dec = int(input("請輸入十進制整數:\n"))
print("轉換后的二進制數是:")
while dec != 0:
binStack.push(dec%2)
dec //= 2
while binStack.isEmpty() == True:
print("{}".format(binStack.pop()), end="")
else:
print("\n")
//打印時間
datetime = datetime.datetime.now()
print(datetime.strftime("%Y-%m-%d\n%H:%M:%S"))
//使命令窗口不立即關閉
input("Press Enter to exit…")
運行結果:
原文鏈接:https://blog.csdn.net/guanchazhe55/article/details/125653716
相關推薦
- 2023-05-31 Pandas提取含有指定字符串的行(完全匹配,部分匹配)_python
- 2022-05-20 Windows10或者11 使用Administrator登錄
- 2022-03-29 帶你了解C++中vector的用法_C 語言
- 2022-08-10 .Net使用Cancellation?Framework取消并行任務_實用技巧
- 2022-01-11 slice、substring、substr比較
- 2022-04-10 SpringBoot 導入插件報錯 Cannot resolve plugin org.spring
- 2022-04-21 Python?數據類型中的字符串和數字_python
- 2024-01-27 什么是DTO ,DTO 有什么作用
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支