Java - Recursion Program - Convert a base 10 number to any Base

后端 未结 5 652
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 07:30

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

5条回答
  •  醉酒成梦
    2021-02-06 07:44

    public class Converter {
    
        private static char symbols[] = new char[] { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T' };
    
        public static void main ( String args[] )
        {
                     Converter converter = new Converter ();
            System.out.println( converter.convert ( 31, 16 ));
        }
    
        public String convert ( int number, int base )
        {
            return convert(number, base, 0, "" );
        }
    
        private String convert ( int number, int base, int position, String result )
        {
            if ( number < Math.pow(base, position + 1) )
            {
                return symbols[(number / (int)Math.pow(base, position))] + result;
            }
            else
            {
                int remainder = (number % (int)Math.pow(base, position + 1));
                return convert (  number - remainder, base, position + 1, symbols[remainder / (int)( Math.pow(base, position) )] + result );
            }
        }
    }
    

    This will convert from Base 2 to Base 36, although you could expand it by adding more symbols.

提交回复
热议问题