Python和C語言利用棧分別實現(xiàn)進制轉(zhuǎn)換
問題描述
利用棧的數(shù)據(jù)結(jié)構(gòu)實現(xiàn)將十進制數(shù)轉(zhuǎn)換成二進制數(shù)
C語言實現(xiàn)
順序表的存儲結(jié)構(gòu)實現(xiàn)棧
代碼:
#include <stdlib.h> #include <stdio.h> #define STACK_INIT_SIZE 100//棧初始開辟空間大小 #define STACK_INCREMENT 10 //棧追加空間大小 //棧的結(jié)構(gòu)體 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; } //主函數(shù) void main() { int dec; binStack bs = stack_init(); printf("請輸入十進制整數(shù):\n"); scanf("%d", &dec); while(dec) { push(&bs, dec%2); dec /= 2; } printf("轉(zhuǎn)換后的二進制數(shù)是:\n"); while(bs.top != bs.base) { printf("%d", pop(&bs)); } printf("\n\n"); system("date /T"); system("TIME /T"); system("pause"); exit(0); }
運行結(jié)果:
Python實現(xiàn)
對于stack我們可以使用python內(nèi)置的list實現(xiàn)(也可以用鏈表實現(xiàn)),因為list是屬于線性數(shù)組,在末尾插入和刪除一個元素所使用的時間都是O(1),這非常符合stack的要求。
代碼:
import datetime //顯示時間引入的庫 import time// from pip._vendor.distlib.compat import raw_input //使命令窗口不立即關(guān)閉引入的庫 //棧類 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("請輸入十進制整數(shù):\n")) print("轉(zhuǎn)換后的二進制數(shù)是:") 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")) //使命令窗口不立即關(guān)閉 input("Press Enter to exit…")
運行結(jié)果:
以上就是Python和C語言利用棧分別實現(xiàn)進制轉(zhuǎn)換的詳細內(nèi)容,更多關(guān)于Python進制轉(zhuǎn)換的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。