LeetCode 3531 - Count Covered Buildings

A single-precision floating point number in MIX, as defined in Section 4.2.1, consists of a sign byte, an exponent field, and a normalized fraction stored in one word.

LeetCode Problem 3531

Difficulty: 🟡 Medium
Topics: Array, Hash Table, Sorting

Solution

Solution

A single-precision floating point number in MIX, as defined in Section 4.2.1, consists of a sign byte, an exponent field, and a normalized fraction stored in one word. A double-precision floating point number in format (1) consists of the same sign and exponent structure, but with an eight-byte fraction split across two words, the most significant five fraction bytes followed by the least significant five fraction bytes.

The conversion from single precision to double precision requires preservation of numerical value, which is achieved by embedding the single-precision fraction into the high-order part of the double-precision fraction and filling the remaining low-order fraction bytes with zeros. The exponent must be copied without change except for the difference in representation field location, since both formats use excess-$b^2/2$ encoding.

Let the single-precision number be stored in a standard floating representation $(s, e, f_1, f_2, f_3, f_4)$ with normalized fraction. The corresponding double-precision representation is $(s, e, f_1, f_2, f_3, f_4, 0, 0, 0, 0)$, since appending zeros does not alter the value of the fraction and preserves normalization in the sense required for Program A and Program M.

The subroutine must therefore perform a word transfer of the exponent and high-order fraction bytes, followed by explicit zeroing of the additional fraction bytes introduced by the double-precision format. No renormalization is required because the leading nonzero byte of the fraction is unchanged and remains in the correct position.

The inverse conversion from double precision to single precision requires truncation of the low-order fraction bytes, together with possible normalization adjustment if truncation produces a leading zero in the retained single-precision fraction. Let the double-precision fraction be $(f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8)$ normalized so that $f_1 \neq 0$. The single-precision fraction is obtained by selecting $(f_1, f_2, f_3, f_4)$ and discarding $(f_5, f_6, f_7, f_8)$. If $(f_1, f_2, f_3, f_4)$ becomes zero, the exponent must be set to zero as in the zero-handling case of DNORM, otherwise the exponent is unchanged.

The correctness follows from the positional representation of the fraction in base $b$: the discarded bytes contribute only terms of order at most $b^{-5}$ relative to the retained part, hence they are representationally absent in the single-precision format without affecting the encoding of the retained leading digits.

This completes the construction of both conversion routines. ∎