Problem 507400 · medium · Phase 05 Advanced Algorithms & Graphs

Numerals for Positive and Negative Bases

number theory · positional notation · divmod

Write the integer n in base b and return the digit string (most significant digit first). The base may be negative: in base -2, the digit string "11010" means 1*16 + 1*(-8) + 0*4 + 1*(-2) + 0*1 = 6. With a negative base every integer, positive or negative, has a representation using only digits 0 .. |b| - 1 and no sign. With a positive base, negative numbers get a leading "-". Zero is "0".

Examples

Input:  n = 6, b = -2
Output: "11010"
Input:  n = -13, b = 3
Output: "-111"
Input:  n = -1, b = -2
Output: "11"
Explanation: 1*(-2) + 1*1 = -1.

Constraints

  • -10**18 <= n <= 10**18, 2 <= |b| <= 10.
  • Target complexity: O(number of digits).

Goals

  • Convert with repeated division and remainders
  • Fix negative remainders when the base is negative
  • Handle zero and negative numbers in positive bases
Starting Python…