Convert a Number to Any Base

medium Math and Number Theory

Problem

Read n and a base b (2 to 36). Print n in base b. Digits above 9 are written with the small letters a, b, c, ... (a = 10, z = 35). For n = 0 print 0.

Constraints

  • 0 <= n <= 10^15
  • 2 <= b <= 36

Examples

Input

255 16

Output

ff

Input

10 2

Output

1010

Solutions

Best approachTime O(log n)Space O(log n)

The remainders of repeated division by b are the digits from the least significant to the most significant. Java also has Long.toString(n, radix) and Python has no direct function for every base, so the loop is worth knowing.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Convert a number.
 * Input   : Two integers: n and the base.
 * Output  : The digits.
 * Approach: Repeated division.
 * Time    : O(log n)
 * Space   : O(log n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(long a, long b) {
        // Step 1: A number in base b is found by repeated division. The remainders are the digits, from right to left.
        if (a == 0) {
            return "0";
        }
        String digits = "0123456789abcdefghijklmnopqrstuvwxyz";
        StringBuilder text = new StringBuilder();
        long remaining = a;

        // Step 2: The remainder after division by b is the next digit. Then divide by b.
        while (remaining > 0) {
            text.append(digits.charAt((int) (remaining % b)));
            remaining /= b;
        }

        // Step 3: The digits came out in reverse order, so we reverse them.
        return text.reverse().toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. In which order do the digits come out?