java 堆栈应用一 十进制转M进制

十进制整数转换为二进制整数十进制整数转换为二进制整数采用"除2取余,逆序排列"法

同理一个10进制数转M进制的原理是:"除M取余,逆序排列

数组实现的堆栈:

public class ArrayStack2<T>
{
	private T[] stack;
	private int top=-1;
	public ArrayStack2()
	{
		this.stack=(T[]) new Object[10];
		this.top=-1;
	}
	public ArrayStack2(int size)
	{
		this.stack=(T[]) new Object[size];
		this.top=-1;
	}
	//进栈
	public boolean push(T t)
	{
		//栈满了,返回false 表示不能再进栈
		if(top==stack.length-1) return false;
		stack[++top]=t;
		return true;//返回真表示进栈成功
	}
	//出栈
	public T pop()
	{
		//栈为空,返回null
		if(top==-1) return null;
		return stack[top--];//返回栈顶,之后top减一
	}
	public T peek()
	{
		if(top==-1) return null;
		return stack[top];
	}
	//判空
	public boolean isEmpty()
	{
		return top==-1;
	}
	//判满
	public boolean isFull()
	{
		return top==stack.length-1;
	}

	// 查找栈中的元素 int search(Object o)
	public int search(Object object) {
		int top1 = top;
		while (!stack[top1].equals(object)) {
			top1--;
			if (top1 == -1)
				return Integer.MIN_VALUE;
		}
		return top1;
	}
	public void showSearch(int searchnum)
	{
		int location=search(searchnum);
//		System.out.println("location="+location);
		if(location==Integer.MIN_VALUE)
			System.out.println("栈中没有"+searchnum+"这个元素");
		else 
			System.out.println("栈中有"+searchnum+"这个元素"+"位置为:"+location);
	}
}
进制转换:

public class UseOfStackTest {
	public static void main(String[] args) {
		System.out.println("进制转换堆栈用于进制");
		int decimalNum=16;
		int decimalNum1=decimalNum;
		int binaryRidax=16;//2进制基数
		ArrayStack2<Integer> binaryCode=new ArrayStack2<Integer>();
		int yushu=0;
		while(decimalNum>0)//商为零结束
		{
			yushu=decimalNum%binaryRidax;//求余数
			binaryCode.push(yushu);//求商
			decimalNum=decimalNum/binaryRidax;//被除数为商
		}
		System.out.print(decimalNum1+"的"+binaryRidax+"进制代码为:");
		int code=0;
		for(int i=0;!binaryCode.isEmpty();i++)
		{
			code=binaryCode.pop();
			if(code<=9)
				System.out.print(code+" ");
			else
				System.out.println((char)(code-10+'A'));
		}System.out.println();
		
	}
}
结果:

进制转换堆栈用于进制
16的16进制代码为:1 0


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值