[DataStructures] 스택(Stack) - 스택을 이용한 이진수변경(ConvertDecimalIntoBinary)
Algorithm&DataStructures/Stack 2016. 11. 18. 11:12스택(Stack) - 스택을 이용한 이진수변경(ConvertDecimalIntoBinary)
- 십 진수를 이진 수로 변경한다
1. DynamicStackImpl.class
class
DynamicStackImp{
private
int
top;
private
int
stackSize;
private
int
[] stackArr;
public
DynamicStackImp(
int
size){
this
.top = -
1
;
this
.stackSize = size;
this
.stackArr =
new
int
[stackSize];
}
public
void
push(
int
element){
if
(
this
.isStackFull()){
System.out.println(
"Stack is full"
);
this
.increaseCapacity();
}
stackArr[++top] = element;
}
public
int
pop()
throws
Exception{
if
(
this
.isStackEmpty()){
throw
new
Exception(
"Stack is empty"
);
}
return
stackArr[top--];
}
public
boolean
isStackEmpty(){
return
(top == -
1
);
}
public
boolean
isStackFull(){
return
(top == stackSize -
1
);
}
public
void
increaseCapacity(){
int
[] newArry =
new
int
[stackSize *
2
];
for
(
int
i =
0
; i<stackSize; i++){
newArry[i] = stackArr[i];
}
System.out.println(
"Stack size is extended"
);
this
.stackArr = newArry;
this
.stackSize = stackSize *
2
;
}
}
2. ConvertDecimalIntoBinary.class
1) converter()
public
String converter(
int
element)
throws
Exception{
DynamicStackImp stack =
new
DynamicStackImp(
5
);
StringBuilder add =
new
StringBuilder();
int
remainder =
0
;
int
quotient = element;
boolean
flag =
true
;
while
(flag){
remainder = quotient%
2
;
quotient = quotient/
2
;
stack.push(remainder);
if
(quotient ==
0
|| quotient ==
1
){
stack.push(quotient);
flag =
false
;
}
}
while
(!stack.isStackEmpty()){
add.append(stack.pop());
}
return
add.toString();
}
2) main()
public
static
void
main(String[]args)
throws
Exception{
ConvertDecimalIntoBinary convert =
new
ConvertDecimalIntoBinary();
System.out.println(convert.converter(
41
));
}
'Algorithm&DataStructures > Stack' 카테고리의 다른 글
[DataStructures] 스택(Stack) - 스택을 이용한 괄호 체크(delimiter matching) (0) | 2016.11.17 |
---|---|
[DataStructures] 스택(Stack) - 스택을 이용해 입력된 문자 뒤집기(Reverse a word) (0) | 2016.11.17 |
[DataStructures] 스택(Stack) - 제네릭스택(Stack Using Generic) (0) | 2016.11.17 |
[DataStructures] 스택(Stack) - 동적스택(dynamicStack) (0) | 2016.11.16 |
[DataStructures] 스택(Stack) - 간단자바예제(Simple in java) (0) | 2016.11.16 |