Java - Recursion Program - way to convert an inputted base to base 10 on a given number

时间:2016-10-20 19:41:48

标签: java recursion

I am given a non-recursive method, that I need to modify to make recursive.

This is what I have so far:

public class BaseN {

   public static final int BASEN_ERRNO = -1;

   public static void main(String[] argv) {

      Scanner input = new Scanner(System.in);
      System.out.print("enter number followed by base (e.g. 237 8): ");
      int number = input.nextInt();
      int base = input.nextInt();

      BigInteger answer = basen(number, base);
      System.out.println(number + " base-" + base + " = " + answer);
   }
   static BigInteger basen(int number, int base ) {

        List<Integer> remainder = new ArrayList<>();

        int count = 0;
        String result = "";
        while( number != 0 ) {
            remainder.add( count, number % base != 0 ? number % base : 0 );
            number /= base;
            try {
                result += remainder.get( count );
            } catch( NumberFormatException e ) {
                e.printStackTrace();
            }
        }
        return new BigInteger( new StringBuffer( result ).reverse().toString() );
    }
}

It's converting it to base 10 then the given base. I need it to convert to the given base first then base 10.


UPDATE: I changed around Caetano's code a bit and think I am closer.

static String basen(int number, int base) {

String result = String.valueOf(number % base);
int resultC;
String resultD;

int newNumber = number / base;

if (newNumber != 0)
    result += basen(newNumber, base);
if (newNumber == 0)
  resultC = Integer.parseInt(result);
  resultD = Integer.toString(resultC);

return resultD;

Now when I compile it it gives me an error it says:

BaseN.java:49: error: variable resultC might not have been initialized
  resultD = Integer.toString(resultC);

Am I on the right track here? Any help is appreciated

2 个答案:

答案 0 :(得分:0)

Its hard to tell what you are asking for.

I can only assume that you want to convert from a given base to base 10. The way that you would do this is explained in this page here: MathBits introduction to base 10.

The way explained in this is simple. For each digit in the number you get the base to the power of the position of the digit(reversed) and multiply that by whatever the digit is. Then add all the results. So 237 in base 8 would be

(8^2 * 2) + (8^1 * 3) + (8^0 * 7) = 159

Now you will run in to a problem when you do this with bases higher then 10 since the general notation for digits above 9 is alphabetical letters. However you could get around this by having a list of values such as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F] and compare the digits with this list and get the index of the location of that digit as the number.

I hope this is what you were asking for.


Now then this is code that does what you want it to do. Get a number in a given base and convert it to base 10. However I don't see why you need to use a recursive method for this. If this is some kind of school task or project then please tell us the details because I don't personally see a reason to use recursion. However the fact that your question asks us to modify the code up top to make it recursive then it makes much more sense. Since that code can be edited to be as such.

   public static final int BASEN_ERRNO = -1;

   public static void main(String[] argv) {

      Scanner input = new Scanner(System.in);
      System.out.print("enter number followed by base (e.g. 237 8): ");
      String number = input.next();
      int base = input.nextInt();

      int answer = basen(number, base);

      System.out.println(number + " base-" + base + " = " + answer);
   }

   private static int basen(String number, int base ) {

       int result = 0;

       for(int i = 0; i < number.length(); i++) {
           int num = Integer.parseInt(number.substring(i, i + 1));

           result += Math.pow(base, number.length() - i - 1) * num;
       }

       return result;

   }

However what I think that you want is actually this which shows recursion but instead of converting from base given to base 10 it converts from base 10 to base given. Which is exactly what the code you showed does but uses recursion. Which means '512 6' will output '2212'

public static final int BASEN_ERRNO = -1;

public static void main(String[] argv) {

    Scanner input = new Scanner(System.in);
    System.out.print("enter number followed by base (e.g. 237 8): ");
    int number = input.nextInt();
    int base = input.nextInt();

    String answer = new StringBuffer(basen(number, base)).reverse().toString();

    System.out.println(number + " base-" + base + " = " + answer);
}

static String basen(int number, int base) {

    String result = String.valueOf(number % base);

    int newNumber = number / base;

    if (newNumber != 0)
        result += basen(newNumber, base);

    return result;
}

答案 1 :(得分:0)

我想出了一种递归方式。谢谢所有提供帮助的人。我最终在基础上使用了Math.pow,并将数字-1的长度设置为指数增加的方式。 Math.pow将结果放在双格式中,所以我只是将它转换回int。我的教授给了我100%的答案,所以我想它也适用于其他人。

public static int basen(int number, int base) {

  String numberStr;
  int numberL;
  char one;
  String remainder;
  int oneInt;
  int remainderInt;
  double power;
  int powerInt;

  numberStr = Integer.toString(number);
  numberL = numberStr.length();
  if(numberL > 1){
     one = numberStr.charAt(0);
     remainder = numberStr.substring(1);
     oneInt = Character.getNumericValue(one);
     remainderInt = Integer.parseInt(remainder);

     power = Math.pow(base, (numberL - 1));
     powerInt = (int)power;
     return ((oneInt * powerInt) + (basen(remainderInt, base)));
  }
  else{
     return number;
  }
 }