1824. Base-B Reader

Easy1.5 points estimatedMathsStringSimulation3 hints

A hardware lab prints its counter readings in whatever base the device uses, anywhere from base 2 up to base 36. The digits are 0 to 9 followed by the lowercase letters a to z, so a stands for 10 and z for 35. A reading can start with a single minus sign to show a negative value.

Given the text digits and the integer base, return the value of the reading as an ordinary integer. Every digit is smaller than base, a reading has no leading zeros unless it is the single digit 0, and a reading is never negative zero. Aim for O(n) time and O(1) extra space, where n is the length of digits.

Example 1

Input:
digits = "1172", base = 8
Output:
634
Explanation:

1*512 + 1*64 + 7*8 + 2 = 634.

Example 2

Input:
digits = "ff", base = 16
Output:
255
Explanation:

f is 15, so 15*16 + 15 = 255.

Example 3

Input:
digits = "-z", base = 36
Output:
-35
Explanation:

z is 35 and the minus sign is kept, so the value is -35.

Constraints

2 ≤ base ≤ 36

1 ≤ digits.length ≤ 11, including the optional leading '-'; at most 10 digits

every digit is smaller than base; no leading zeros except the single string "0"; "-0" does not occur

the answer fits in a double without losing precision

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…