Write a Java program that will convert a positive integer in a specified base to
ID: 3584291 • Letter: W
Question
Write a Java program that will convert a positive integer in a specified base to another base. The program should work for bases 2 to 25, using case-insensitive alphabetic letters a-o for digits beyond 9. Values of the numbers to be converted should not exceed the equivalent of 2^63-1, and the number should be verified to contain valid digits for the given base. You may not use any existing class or function to do the conversion; you must program the conversion algorithm yourself. Sample I/O ------------- Enter base of the number to be converted (0 to quit): 2 Enter the number to be converted: 101010 Enter the target base: 10 101010 base 2 equals 42 base 10 Enter base of the number to be converted (0 to quit): 16 Enter the number to be converted: 1a2B Enter the target base: 2 1a2b base 16 equals 1101000101011 base 2 Enter base of the number to be converted (0 to quit): 0Explanation / Answer
def base10toN(num,n): """Change a to a base-n number. Up to base-36 is supported without special notation.""" num_rep={10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f', 16:'g', 17:'h', 18:'i', 19:'j', 20:'k', 21:'l', 22:'m', 23:'n', 24:'o', 25:'p', 26:'q', 27:'r', 28:'s', 29:'t', 30:'u', 31:'v', 32:'w', 33:'x', 34:'y', 35:'z'} new_num_string='' current=num while current!=0: remainder=current%n if 36>remainder>9: remainder_string=num_rep[remainder] elif remainder>=36: remainder_string='('+str(remainder)+')' else: remainder_string=str(remainder) new_num_string=remainder_string+new_num_string current=current/n return new_num_string
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.