Java - 递归程序 - 将基数为10的数字转换为任何基数 [英] Java - Recursion Program - Convert a base 10 number to any Base

查看:186
本文介绍了Java - 递归程序 - 将基数为10的数字转换为任何基数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用转换将基数为10的数字转换为任何基数。现在这是我提出的代码。我有一种悲伤的感觉,这可能是完全错误的。下图是一个如何进行此过程的示例。

I am trying to convert a base 10 number to any base by using conversion. Right now this is the code I have came up with. I have a sad feeling this may be completely wrong. The image below is an example of how this process should take place.

http:// i854.photobucket.com/albums/ab107/tonytauart/rrrr.png

public static void main(String[] args) {


  int base;
  int number;


    Scanner console = new Scanner(System.in);

    System.out.println("Please enter the base");
        base = console.nextInt();
    System.out.println("Please enter the Number you would like to convert");
        number = console.nextInt();

        System.out.println(Converter(base, number));
}


public static int Converter(int Nbase, int Nnumber){

    int answer;
    int Rcontainer =0;
    int cnt = 0;
    int multiplier;
    int temp;
    double exp;

    if(Nnumber/Nbase == 0){
        cnt++;
        exp = Math.pow(10,cnt); 
        multiplier = (int)exp;
         answer = (Nnumber%Nbase)* multiplier + Rcontainer;


    }
    else
      {
       exp = Math.pow(10,cnt);
       multiplier = (int)exp;
       cnt++;
       temp = Rcontainer;
       Rcontainer = (Nnumber%Nbase)* multiplier + temp;   

       Nnumber = Nnumber/Nbase;
        answer = Converter(Nbase,Nnumber);
       }  
        return answer;
}

}

推荐答案

我刚刚为comp sci类完成了这个问题。我必须递归地解决这个问题:

I just finished doing this problem for a comp sci class. I had to solve this recursively:

public static String convert(int number, int base)
{
    int quotient = number / base;
    int remainder = number % base;

    if (quotient == 0) // base case
    {
        return Integer.toString(remainder);      
    }
    else
    {
        return convert(quotient, base) + Integer.toString(remainder);
    }            
}

这篇关于Java - 递归程序 - 将基数为10的数字转换为任何基数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆