LeetCode 3581 - Count Odd Letters from Number

Algorithm S performs digit-by-digit subtraction in radix without requiring knowledge of whether . It produces digits and a final borrow , where occurs if and only if .

LeetCode Problem 3581

Difficulty: 🟢 Easy
Topics: Hash Table, String, Simulation, Counting

Solution

Solution

Algorithm S performs digit-by-digit subtraction in radix $b$ without requiring knowledge of whether $(u_{n-1}\ldots u_0)b \ge (v{n-1}\ldots v_0)b$. It produces digits $w_0, w_1, \ldots, w{n-1}$ and a final borrow $k \in {0,-1}$, where $k=-1$ occurs if and only if $u < v$.

Assume Algorithm S is executed without prior ordering of the operands, and suppose that at termination the final borrow is $k=-1$. The internal recurrence in step S2 gives, for each $j$,

$$w_j \equiv u_j - v_j + k_j \pmod b, \quad k_{j+1} \in {0,-1},$$

with $k_0=0$ and $k_n=-1$. The identity defining modular reduction in Algorithm S implies that for each digit position,

$$w_j = \begin{cases} u_j - v_j + k_j, & \text{if } u_j - v_j + k_j \ge 0, \ u_j - v_j + k_j + b, & \text{if } u_j - v_j + k_j < 0. \end{cases}$$

When $k_n=-1$, the computed number $(w_{n-1}\ldots w_0)_b$ represents the radix-$b$ complement of the true difference. This follows from the identity in Section 4.3.1 that subtraction with borrow produces a representation congruent modulo $b^n$ to

$$u - v \equiv (w_{n-1}\ldots w_0)_b - b^n.$$

Hence

$$v - u = b^n - (w_{n-1}\ldots w_0)_b.$$

The absolute value of the difference is therefore obtained by transforming the digit string $(w_{n-1}\ldots w_0)_b$ into the radix-$b$ complement of order $n$ and then adding $1$ in radix $b$.

The complement construction is defined digitwise by replacing each digit $w_j$ with

$$w'_j = b-1-w_j, \quad 0 \le j < n.$$

This yields the number $(w'_{n-1}\ldots w'_0)b = (b^n-1) - (w{n-1}\ldots w_0)_b$.

Adding $1$ to this complemented number produces

$$(b^n-1) - (w_{n-1}\ldots w_0)b + 1 = b^n - (w{n-1}\ldots w_0)_b = v - u.$$

This addition is carried out by Algorithm A applied to the digits $w'_j$, starting with initial carry $k \leftarrow 1$ and all higher carries computed in the usual way.

The required correction algorithm is therefore as follows.

Start with the output $(w_{n-1}\ldots w_0)b$ of Algorithm S. If the final borrow is $k=0$, no correction is performed and the result is $(w{n-1}\ldots w_0)_b$. If the final borrow is $k=-1$, replace each digit by $w'j \leftarrow b-1-w_j$ for $0 \le j < n$, then apply Algorithm A to $(w'{n-1}\ldots w'_0)_b$ and the constant $(0\ldots 0 1)_b$ to add $1$.

The output of this second computation is the radix-$b$ representation of $v-u$, which equals the absolute value $|u-v|$ in the case $u<v$. This completes the construction of the complement-based correction algorithm for Algorithm S. ∎