You all are aware of Stacks. It performs two basic operations push and pop. The push operation adds an element to the top of the list, or initializing the stack if it is empty and the pop operation removes an item from the top of the list. Using these operations, we have converted a decimal number into Octal.

- Divide the decimal number by 8
- Treat the division as an integer division. Write down the remainder (in Octal).
- Divide the result again by 8.
- Treat the division as an integer division. Repeat step 2 and 3 until result is 0.
- The Oct value is the digit sequence of the remainders from the last to first.

Octal 0 1 2 3 4 5 6 7

DECIMAL 0 1 2 3 4 5 6 7

**Java version of decimal to hexadecimal is given bellow :**

/** * To change this template, choose Tools | Templates * and open the template in the editor. */ package stack; import java.util.Scanner; /** * * @author ACHCHUTHAN */ public class Decimal2oct extends Stack { int decimal; public Decimal2oct(int n) { super(n); System.out.println("Enter nonnegative integer :"); Scanner input = new Scanner(System.in); decimal = input.nextInt(); } /** * push the value to stack */ public void setHex2Stack() { if (decimal == 0) { push(0); } while (decimal > 0) { int digit = decimal % 8; push(digit); decimal = decimal / 8; } } /** * @return octal string value */ public String getHexa() { String h = ""; while (!isEmpty()) { h = h + pop(); } return h; } public static void main(String args[]) { Decimal2oct d = new Decimal2oct(16); d.setHex2Stack(); d.print(); System.out.println("Octal : " + d.getHexa()); decimal2hexa d2 = new decimal2hexa(16); d2.setHex2Stack(); d2.print(); System.out.println("Octal : " + d2.getHexa()); } }

**Output of this program :**

run:

Enter nonnegative integer :

32

Contents of Stack :

0 | 4 |

Octal : 40

Enter nonnegative integer :

16

Contents of Stack :

0 | 1 |

Octal : 10

BUILD SUCCESSFUL (total time: 5 seconds)

## Comments

## Post a Comment

Thank you for vising Java90.blogspot.com