本文主要是介绍使用顺序栈实现数制转换算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
(1)将N除以d,取其商和余数
(2)判断商是否为零,若商不为零,则将商赋值给N,继续步骤(1),否则,为0,转换结束
package experiment;
public interface IStack {public void clear();//清空public boolean isEmpty();//判空public int length();//长度public Object peek();//取栈顶元素public void push(Object x)throws Exception;//入栈public Object pop();//出栈}
public class SqStack implements IStack {
public Object[] stackElem;//对象数组
private int top;//在非空栈中,top始终指向栈顶元素的下一个储存位置;当栈为空时,top值为0.
public SqStack(int maxSize){top=0;//初始化top为0stackElem=new Object[maxSize];//为栈分配maxSize个储存单位}public void clear() {//清空top=0;}public boolean isEmpty() {//判空return top==0;}@Overridepublic int length() {//元素个数return top;}@Overridepublic Object peek() {//取栈顶元素if(! isEmpty())return stackElem[top-1];//返回栈顶元素elsereturn null;}@Overridepublic void push(Object x) throws Exception {//入栈if(top==stackElem.length)throw new Exception("栈已满");elsestackElem[top++]=x;//先将新的数据元素x压入栈顶,再top增1}@Overridepublic Object pop() {//出栈if(isEmpty())//栈空return null;else//栈非空return stackElem[--top];}public void display(){for(int i=top-1;i>=0;i--)System.out.print(stackElem[i].toString()+"");}import java.util.Scanner;
//进制转化
public class Test2 {
public static void main(String[] args) throws Exception {int maxSize = 100 ;SqStack S = new SqStack(maxSize); System.out.println("请输入一个十进制数字:");Scanner sc = new Scanner(System.in);int N = sc.nextInt();System.out.println("请输入要转换进制:");int d=sc.nextInt();String str="";while(N>0){S.push(N%d);N=N/d;}while(!S.isEmpty()){str=str+S.pop();}System.out.println("转换成"+d+"进制是"+str);}
}
运行结果
这篇关于使用顺序栈实现数制转换算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!