Monday, 10 July 2017

Java Code to covert a decimal number to octal number.

Problem:

Convert a decimal integer to its corresponding octal representation.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DecimalToOctal {

static int n;
List<Character> digits = new ArrayList<Character>();

public static void main(String[] args) {
DecimalToOctal baseConversion = new DecimalToOctal();
baseConversion.getTheNumber();
baseConversion.convertToOctal(n);
baseConversion.printTheResult("the octal number is: ");
}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter decimal value");
n = s.nextInt();
s.close();
}

public void convertToOctal(int n){
int q = n;
int r = 0;
for(int i= 0; (q > 0); i++){
r = q%8;
digits.add(intToChar(r));
q = q/8;
}
}

public void printTheResult(String message){
int number = 0;
for(int i = digits.size() - 1; i >= 0; i--){
number = number * 10 + charToInt(digits.get(i));
}
System.out.println(message + number);
}

private char intToChar(int i)
{
if(i >= 0 && i <= 9)
return (char)(i + 48);
else if(i >= 10 && i <= 35)
return (char)(i + 55);
else
return (char)(i);

}

private int charToInt(char c)
{
if(c >= '0' && c <= '9')
return (int)(c - 48);
else if(c >= 'A' && c <= 'Z')
return (int)(c - 55);
else if(c >= 'a' && c <= 'z')
return (int)(c - 87);
else
return 0;
}
}


Output:

enter decimal value
258
the octal number is: 402


enter decimal value
93
the octal number is: 135



No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...