栈
public class MyStack {
private int [ ] array;
private static int size;
private static final int INITSIZE = 100 ;
public MyStack ( ) {
array = new int [ INITSIZE] ;
}
private void ensureCapacity ( ) {
if ( size == array. length) {
Arrays. copyOf ( array, array. length+ ( array. length>> 1 ) ) ;
}
}
public boolean isEmpty ( ) {
return this . size == 0 ;
}
public void push ( int value) {
ensureCapacity ( ) ;
array[ size] = value;
size++ ;
}
public void pop ( ) {
if ( isEmpty ( ) ) {
return ;
}
size-- ;
}
public int peek ( ) {
if ( size == 0 ) {
throw new EmptyStackException ( ) ;
}
return array[ size- 1 ] ;
}
}
进制转换
public class HexTranslated {
private MyStack myStack = new MyStack ( ) ;
public void go ( int value, int mod) {
int conslut = value;
int remainder = 0 ;
while ( conslut >= mod) {
remainder = conslut % mod;
myStack. push ( remainder) ;
conslut /= mod;
}
myStack. push ( conslut) ;
}
public StringBuilder show ( ) {
StringBuilder stringBuilder = new StringBuilder ( ) ;
System. out. print ( "转换结果为: " ) ;
while ( ! myStack. isEmpty ( ) ) {
stringBuilder. append ( myStack. peek ( ) + " " ) ;
myStack. pop ( ) ;
}
return stringBuilder;
}
}
测试
public class Test {
public static void main ( String[ ] args) {
HexTranslated hexTranslated = new HexTranslated ( ) ;
hexTranslated. go ( 12 , 2 ) ;
System. out. println ( hexTranslated. show ( ) ) ;
hexTranslated. go ( 58 , 8 ) ;
System. out. println ( hexTranslated. show ( ) ) ;
}
}
测试结果