Sunday, October 23, 2011

Convert a decimal (base 10) number to any base (Java)

//This Java program accepts a decimal number
//i.e. base 10 number from the user and then
//accepts another number from the user and then
//converts the first number to a number whose base
//is the numerical value of the second number.
//NOTE : The second number should be
//between 2 and 10 only.
import java.util.*;
class convertToBase
{
public static void main()
{
System.out.print("Enter the decimal number : ");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.print("Enter the base you would like to convert the number to : ");
int b=sc.nextInt();
int q=n,r;
String ans="";
while(q!=0)
{
r=q%b;
ans=r+ans;
q=q/b;
}
System.out.println(ans);
}
}
//Author : Mayank Rajoria

No comments:

Post a Comment