十进制整数转换为二进制整数十进制整数转换为二进制整数采用"除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