Problem:
Write a Java program that will convert a number(x) in base r to base 10.
The program should also meet the following requirements:
· Base r is an input and must be validated ; r is from 2 to 9 only
· The number x is an input and must be stored in an int type variable. Do not convert x to
string.
· Use of String type variable is not allowed.
· Use of arrays is not allowed.
· Use of built-in method that converts a given number to another base is not allowed.
· Your program should execute for as long as the user wants to continue
Assume that the user will input a valid number.
Note: This program converts X^r to Y^10
Where :
X^r - a number in base r
r – is from 2 to 9 only
Y^10 – the equivalent number in base 10
class Main
{
  public static void main(String[] args)
  {
    String s1 = "1010";Â
    String s2 = "2314";
    String s3 = "435";
    System.out.println(convert_to_Base(s1,2));
    System.out.println(convert_to_Base(s2,4));
    System.out.println(convert_to_Base(s3,5));
  }
  private static final String SYMBOLS = "0123456789ABCDEF";
  public static long convert_to_Base(String num, int b)
  {
    long res = 0;
    int pos = num.length();Â
    for (char c : num.toCharArray())
    {
      int value = SYMBOLS.indexOf(c);
      res += value * pow(b,--pos);Â
    }
    return res;
  }
  private static long pow(int val, int x)
  {
    if (x == 0) return 1;
    return val * pow(val,x-1);
  }
}
Comments
Leave a comment