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
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