File size: 768 Bytes
9438a57 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import java.util.*;
/**
* Integer Base Conversion
* base-conversion
*
*
* Input:
* num: A base-10 integer to convert.
* b: The target base to convert it to.
*
* Precondition:
* num > 0, 2 <= b <= 36.
*
* Output:
* A string representing the value of num in base b.
*
* Example:
* >>> to_base(31, 16)
* '1F'
*
* @author derricklin
*/
public class TO_BASE {
public static String to_base(int num, int b) {
String result = "";
String alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i;
while (num > 0) {
i = num % b;
num = num / b; // floor division?
result = String.valueOf(alphabet.charAt(i))+result;
}
return result;
}
}
|