Retranslate the complete English edition from Simplified Chinese (#2010)

* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
This commit is contained in:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -1,66 +1,66 @@
# Basic Data Types
# Basic data types
When we talk about data stored in computers, we think of various forms such as text, images, videos, audio, 3D models, and more. Although these kinds of data are organized in different ways, they are all composed of various basic data types.
Computer data comes in many forms: text, images, video, audio, 3D models, and more. Although organized differently, all these forms are built from basic data types.
**Basic data types are types that the CPU can directly operate on**, and they are directly used in algorithms, mainly including the following.
**Basic data types are types on which the CPU can operate directly** and which algorithms use directly. The main types include the following.
- Integer types `byte`, `short`, `int`, `long`.
- Floating-point types `float`, `double`, used to represent decimal numbers.
- Character type `char`, used to represent letters, punctuation marks, and even emojis in various languages.
- Boolean type `bool`, used to represent "yes" and "no" judgments.
- Integer types: `byte`, `short`, `int`, and `long`.
- Floating-point types: `float` and `double`, used to represent fractional numbers.
- The character type `char`, used for letters in different languages, punctuation, and even emoji.
- The Boolean type `bool`, used for yes-or-no values.
**Basic data types are stored in binary form in computers**. A binary digit is one bit. In most modern operating systems, $1$ byte consists of $8$ bits.
**Basic data types are stored in binary form**. One binary digit is $1$ bit. In the vast majority of modern operating systems, $1$ byte consists of $8$ bits.
The range of values for basic data types depends on the size of the space they occupy. Below is an example using Java.
A basic data type's value range depends on the space it occupies. Taking Java as an example:
- Integer type `byte` occupies $1$ byte = $8$ bits, and can represent $2^{8}$ numbers.
- Integer type `int` occupies $4$ bytes = $32$ bits, and can represent $2^{32}$ numbers.
- An integer `byte` occupies $1$ byte = $8$ bits and can represent $2^{8}$ distinct values.
- An integer `int` occupies $4$ bytes = $32$ bits and can represent $2^{32}$ distinct values.
The following table lists the space occupied, value ranges, and default values of various basic data types in Java. You don't need to memorize this table; a general understanding is sufficient, and you can refer to it when needed.
The table below lists storage sizes, value ranges, and default values for Java's basic data types. There is no need to memorize it; understand the general picture and refer back when needed.
<p align="center"> Table <id> &nbsp; Space occupied and value ranges of basic data types </p>
<p align="center"> Table <id> &nbsp; Storage sizes and value ranges of basic data types </p>
| Type | Symbol | Space Occupied | Minimum Value | Maximum Value | Default Value |
| ---------- | -------- | -------------- | ------------------------ | ----------------------- | -------------- |
| Integer | `byte` | 1 byte | $-2^7$ ($-128$) | $2^7 - 1$ ($127$) | $0$ |
| | `short` | 2 bytes | $-2^{15}$ | $2^{15} - 1$ | $0$ |
| | `int` | 4 bytes | $-2^{31}$ | $2^{31} - 1$ | $0$ |
| | `long` | 8 bytes | $-2^{63}$ | $2^{63} - 1$ | $0$ |
| Float | `float` | 4 bytes | $1.175 \times 10^{-38}$ | $3.403 \times 10^{38}$ | $0.0\text{f}$ |
| | `double` | 8 bytes | $2.225 \times 10^{-308}$ | $1.798 \times 10^{308}$ | $0.0$ |
| Character | `char` | 2 bytes | $0$ | $2^{16} - 1$ | $0$ |
| Boolean | `bool` | 1 byte | $\text{false}$ | $\text{true}$ | $\text{false}$ |
| Type | Name | Storage size | Minimum value | Maximum value | Default value |
| ------ | -------- | -------- | ------------------------ | ----------------------- | -------------- |
| Integer | `byte` | 1 byte | $-2^7$ ($-128$) | $2^7 - 1$ ($127$) | $0$ |
| | `short` | 2 bytes | $-2^{15}$ | $2^{15} - 1$ | $0$ |
| | `int` | 4 bytes | $-2^{31}$ | $2^{31} - 1$ | $0$ |
| | `long` | 8 bytes | $-2^{63}$ | $2^{63} - 1$ | $0$ |
| Floating-point | `float` | 4 bytes | $1.175 \times 10^{-38}$ | $3.403 \times 10^{38}$ | $0.0\text{f}$ |
| | `double` | 8 bytes | $2.225 \times 10^{-308}$ | $1.798 \times 10^{308}$ | $0.0$ |
| Character | `char` | 2 bytes | $0$ | $2^{16} - 1$ | $0$ |
| Boolean | `bool` | 1 byte | $\text{false}$ | $\text{true}$ | $\text{false}$ |
Please note that the table above applies specifically to Java's basic data types. Each programming language has its own type definitions, and their space usage, value ranges, and default values may vary.
The table above describes Java's basic data types. Each programming language defines its own types, whose sizes, value ranges, and default values may differ.
- In Python, the integer type `int` can be of any size, limited only by available memory; the floating-point type `float` is double-precision 64-bit; there is no `char` type, a single character is actually a string `str` of length 1.
- C and C++ do not explicitly specify the size of basic data types, which varies by implementation and platform. The above table follows the LP64 [data model](https://en.cppreference.com/w/cpp/language/types#Properties), which is used in Unix 64-bit operating systems including Linux and macOS.
- The size of character `char` is 1 byte in C and C++, and in most programming languages it depends on the specific character encoding method, as detailed in the "Character Encoding" section.
- Even though representing a boolean value requires only 1 bit ($0$ or $1$), it is usually stored as 1 byte in memory. This is because modern computer CPUs typically use 1 byte as the minimum addressable memory unit.
- In Python, an `int` can be arbitrarily large, limited only by available memory. A `float` is a 64-bit double-precision number. There is no `char` type: a single character is a `str` of length 1.
- C and C++ do not fix the sizes of basic data types; they vary by implementation and platform. The table above follows the LP64 [data model](https://en.cppreference.com/w/cpp/language/types#Properties), used by 64-bit Unix operating systems including Linux and macOS.
- A `char` occupies 1 byte in C and C++. In most programming languages, character size depends on the encoding used; see the character encoding section.
- Although a Boolean needs only 1 bit ($0$ or $1$), it usually occupies 1 byte in memory because modern CPUs typically use a byte as the smallest addressable memory unit.
So, what is the relationship between basic data types and data structures? We know that data structures are ways of organizing and storing data in computers. Here, the emphasis is on the "structure", not the "data".
How do basic data types relate to data structures? A data structure is a way to organize and store data in a computer. The emphasis is on structure, rather than the data itself.
If we want to represent "a row of numbers", we naturally think of using an array. This is because the linear structure of an array can represent the adjacency and order relationships of numbers, but whether the stored content is integer `int`, floating-point `float`, or character `char` is unrelated to the "data structure".
To represent a row of numbers, an array comes naturally to mind. Its linear structure captures adjacency and ordering, regardless of whether the stored values are integers (`int`), fractional numbers (`float`), or characters (`char`).
In other words, **basic data types provide the "content type" of data, while data structures provide the "organization method" of data**. For example, in the following code, we use the same data structure (array) to store and represent different basic data types, including `int`, `float`, `char`, `bool`, etc.
In other words, **basic data types specify what kind of data is stored, while data structures specify how it is organized**. The following code uses the same data structure, an array, for different basic types, including `int`, `float`, `char`, and `bool`.
=== "Python"
```python title=""
# Initialize arrays using various basic data types
# Initialize arrays with different basic data types
numbers: list[int] = [0] * 5
decimals: list[float] = [0.0] * 5
# In Python, characters are actually strings of length 1
# A Python character is a string of length 1
characters: list[str] = ['0'] * 5
bools: list[bool] = [False] * 5
# Python lists can freely store various basic data types and object references
# Python lists can hold different basic data types and object references
data = [0, 0.0, 'a', False, ListNode(0)]
```
=== "C++"
```cpp title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
int numbers[5];
float decimals[5];
char characters[5];
@@ -70,7 +70,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Java"
```java title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
int[] numbers = new int[5];
float[] decimals = new float[5];
char[] characters = new char[5];
@@ -80,7 +80,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "C#"
```csharp title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
int[] numbers = new int[5];
float[] decimals = new float[5];
char[] characters = new char[5];
@@ -90,7 +90,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Go"
```go title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
var numbers = [5]int{}
var decimals = [5]float64{}
var characters = [5]byte{}
@@ -100,7 +100,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Swift"
```swift title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
let numbers = Array(repeating: 0, count: 5)
let decimals = Array(repeating: 0.0, count: 5)
let characters: [Character] = Array(repeating: "a", count: 5)
@@ -110,14 +110,14 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "JS"
```javascript title=""
// JavaScript arrays can freely store various basic data types and objects
// JavaScript arrays can hold different basic data types and objects
const array = [0, 0.0, 'a', false];
```
=== "TS"
```typescript title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
const numbers: number[] = [];
const characters: string[] = [];
const bools: boolean[] = [];
@@ -126,7 +126,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Dart"
```dart title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
List<int> numbers = List.filled(5, 0);
List<double> decimals = List.filled(5, 0.0);
List<String> characters = List.filled(5, 'a');
@@ -136,7 +136,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Rust"
```rust title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
let numbers: Vec<i32> = vec![0; 5];
let decimals: Vec<f32> = vec![0.0; 5];
let characters: Vec<char> = vec!['0'; 5];
@@ -146,7 +146,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "C"
```c title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
int numbers[10];
float decimals[10];
char characters[10];
@@ -156,7 +156,7 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Kotlin"
```kotlin title=""
// Initialize arrays using various basic data types
// Initialize arrays with different basic data types
val numbers = IntArray(5)
val decinals = FloatArray(5)
val characters = CharArray(5)
@@ -166,10 +166,10 @@ In other words, **basic data types provide the "content type" of data, while dat
=== "Ruby"
```ruby title=""
# Ruby lists can freely store various basic data types and object references
# Ruby arrays can hold different basic data types and object references
data = [0, 0.0, 'a', false, ListNode(0)]
```
??? pythontutor "Visualized Execution"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A7%8D%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E6%9D%A5%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E7%BB%84%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20*%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20*%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%AD%97%E7%AC%A6%E5%AE%9E%E9%99%85%E4%B8%8A%E6%98%AF%E9%95%BF%E5%BA%A6%E4%B8%BA%201%20%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%0A%20%20%20%20characters%20%3D%20%5B'0'%5D%20*%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20*%205%0A%20%20%20%20%23%20Python%20%E7%9A%84%E5%88%97%E8%A1%A8%E5%8F%AF%E4%BB%A5%E8%87%AA%E7%94%B1%E5%AD%98%E5%82%A8%E5%90%84%E7%A7%8D%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%92%8C%E5%AF%B9%E8%B1%A1%E5%BC%95%E7%94%A8%0A%20%20%20%20data%20%3D%20%5B0,%200.0,%20'a',%20False,%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked%20list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20successor%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20arrays%20with%20different%20basic%20data%20types%0A%20%20%20%20numbers%20%3D%20%5B0%5D%20%2A%205%0A%20%20%20%20decimals%20%3D%20%5B0.0%5D%20%2A%205%0A%20%20%20%20%23%20A%20Python%20character%20is%20a%20string%20of%20length%201%0A%20%20%20%20characters%20%3D%20%5B%270%27%5D%20%2A%205%0A%20%20%20%20bools%20%3D%20%5BFalse%5D%20%2A%205%0A%20%20%20%20%23%20Python%20lists%20can%20hold%20different%20basic%20data%20types%20and%20object%20references%0A%20%20%20%20data%20%3D%20%5B0%2C%200.0%2C%20%27a%27%2C%20False%2C%20ListNode%280%29%5D&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -1,85 +1,85 @@
# Character Encoding *
# Character encoding *
In computers, all data is stored in binary form, and character `char` is no exception. To represent characters, we need to establish a "character set" that defines a one-to-one correspondence between each character and binary numbers. With a character set, computers can convert binary numbers to characters by looking up the table.
All computer data is stored as binary numbers, including characters of type `char`. To represent characters, we need a character set that assigns each character a unique binary number. The computer can then convert numbers to characters by looking them up.
## ASCII Character Set
## ASCII character set
<u>ASCII code</u> is the earliest character set, with the full name American Standard Code for Information Interchange. It uses 7 binary bits (the lower 7 bits of one byte) to represent a character, and can represent a maximum of 128 different characters. As shown in the figure below, ASCII code includes uppercase and lowercase English letters, numbers 0 ~ 9, some punctuation marks, and some control characters (such as newline and tab).
<u>ASCII</u>, short for American Standard Code for Information Interchange, was the earliest character set. It uses 7 bits (the lower 7 bits of a byte) per character, allowing up to 128 characters. As shown in the figure below, ASCII includes uppercase and lowercase English letters, digits 0 ~ 9, punctuation, and control characters such as newlines and tabs.
![ASCII code](character_encoding.assets/ascii_table.png)
![ASCII codes](character_encoding.assets/ascii_table.png)
However, **ASCII code can only represent English**. With the globalization of computers, a character set called <u>EASCII</u> that can represent more languages emerged. It expands from the 7-bit basis of ASCII to 8 bits, and can represent 256 different characters.
However, **ASCII can represent only English text**. As computers spread worldwide, <u>EASCII</u> character sets emerged to support more languages. Extending ASCII from 7 bits to 8 allowed 256 distinct characters.
Worldwide, a batch of EASCII character sets suitable for different regions have appeared successively. The first 128 characters of these character sets are unified as ASCII code, and the last 128 characters are defined differently to adapt to the needs of different languages.
Different regions developed their own EASCII character sets. The first 128 characters remained identical to ASCII, while the remaining 128 varied to meet different languages' needs.
## GBK Character Set
## GBK character set
Later, people found that **EASCII still could not provide enough characters for many languages**. For example, there are nearly one hundred thousand Chinese characters, and several thousand are used in everyday life. In 1980, the China National Standardization Administration released the <u>GB2312</u> character set, which included 6,763 Chinese characters, basically meeting the needs of computer processing for Chinese.
Eventually, **even EASCII proved too small for many languages**. Chinese, for example, has nearly 100,000 characters, with thousands used daily. In 1980, China's National Bureau of Standards released <u>GB2312</u>, containing 6,763 Chinese characters and meeting most basic needs for processing Chinese text.
However, GB2312 cannot handle some rare characters and traditional Chinese characters. The <u>GBK</u> character set is an extension based on GB2312, which includes a total of 21,886 Chinese characters. In the GBK encoding scheme, ASCII characters are represented using one byte, and Chinese characters are represented using two bytes.
GB2312 could not handle some rare and traditional characters. <u>GBK</u> extended it to 21,886 Chinese characters. In GBK encoding, ASCII characters use one byte, and Chinese characters use two.
## Unicode Character Set
## Unicode character set
With the vigorous development of computer technology, character sets and encoding standards flourished, which brought many problems. On the one hand, these character sets generally only define characters for specific languages and cannot work normally in multilingual environments. On the other hand, multiple character set standards exist for the same language, and if two computers use different encoding standards, garbled characters will appear during information transmission.
As computing grew, character sets and encoding standards proliferated, creating problems. Most covered only particular languages and did not work well in multilingual settings. Multiple standards also existed for the same language, so exchanging text between computers using different encodings could produce garbled text.
Researchers of that era thought: **If a sufficiently complete character set were released to include all languages and symbols in the world, wouldn't that solve problems in cross-language environments and eliminate garbled text**? Driven by this idea, a large and comprehensive character set, Unicode, was born.
Researchers asked: **could a sufficiently comprehensive character set, containing all the world's languages and symbols, solve both multilingual compatibility and garbled-text problems**? This idea led to Unicode.
<u>Unicode</u>, or Unified Code, can theoretically accommodate over one million characters. It is committed to including characters from around the world into a unified character set, providing a universal character set to handle and display various language texts, reducing garbled character problems caused by different encoding standards. Since its release in 1991, Unicode has continuously expanded to include new languages and characters. As of September 2022, Unicode has included 149,186 characters, including characters, symbols, and even emojis from various languages.
<u>Unicode</u>, whose Chinese name means "unified code", can theoretically accommodate over a million characters. It aims to bring the world's characters into one universal set for processing and displaying different languages, reducing garbled text caused by incompatible standards. Since its release in 1991, it has continued adding languages and characters. As of September 2022, Unicode contained 149,186 characters, including letters, symbols, and emoji.
As a universal character set, Unicode essentially assigns each character a unique "code point" (character identifier), whose range is U+0000 to U+10FFFF, forming a unified character numbering space. However, **Unicode does not specify how to store these character code points in computers**. We can't help but ask: when Unicode code points of multiple lengths appear simultaneously in a text, how does the system parse the characters? For example, given an encoding with a length of 2 bytes, how does the system determine whether it is one 2-byte character or two 1-byte characters?
As a universal character set, Unicode assigns each character a unique code point, or character number, from U+0000 to U+10FFFF. **It does not, by itself, specify how these code points are stored in a computer**. How can a system parse text containing code points of different lengths? For example, how does it distinguish one two-byte character from two one-byte characters?
For the above problem, **a straightforward solution is to store all characters as equal-length encodings**. As shown in the figure below, each character in "Hello" occupies 1 byte, and each character in "算法" (algorithm) occupies 2 bytes. We can encode all characters in "Hello 算法" as 2 bytes in length by padding the high bits with 0. In this way, the system can parse one character every 2 bytes and restore the content of this phrase.
**One straightforward solution is to store every character in a fixed-width encoding**. In the figure below, each character in "Hello" occupies 1 byte, while each in "算法" occupies 2 bytes. Padding the high bits with zeros lets us encode every character in "Hello 算法" with 2 bytes. The system can then read one character every 2 bytes to recover the phrase.
![Unicode encoding example](character_encoding.assets/unicode_hello_algo.png)
![Example of Unicode encoding](character_encoding.assets/unicode_hello_algo.png)
However, ASCII code has already proven to us that encoding English only requires 1 byte. If the above scheme is adopted, the size of English text will be twice that under ASCII encoding, which is very wasteful of memory space. Therefore, we need a more efficient Unicode encoding method.
ASCII has already shown that English text needs only 1 byte per character. This scheme would double its storage compared with ASCII, wasting memory. We therefore need a more efficient Unicode encoding.
## UTF-8 Encoding
## UTF-8 encoding
Currently, UTF-8 has become the most widely used Unicode encoding method internationally. **It is a variable-length encoding** that uses 1 to 4 bytes to represent a character, depending on the complexity of the character. ASCII characters only require 1 byte, Latin and Greek letters require 2 bytes, commonly used Chinese characters require 3 bytes, and some other rare characters require 4 bytes.
UTF-8 is now the most widely used Unicode encoding worldwide. **It is variable-length**, using 1 to 4 bytes per character depending on the character. ASCII characters need 1 byte, Latin and Greek letters need 2, common Chinese characters need 3, and some less common characters need 4.
The encoding rules of UTF-8 are not complicated and can be divided into the following two cases.
UTF-8's rules have two cases.
- For 1-byte characters, set the highest bit to $0$, and set the remaining 7 bits to the Unicode code point. It is worth noting that ASCII characters occupy the first 128 code points in the Unicode character set. That is to say, **UTF-8 encoding is backward compatible with ASCII code**. This means we can use UTF-8 to parse very old ASCII code text.
- For characters with a length of $n$ bytes (where $n > 1$), set the highest $n$ bits of the first byte to $1$, and set the $(n + 1)$-th bit to $0$; starting from the second byte, set the highest 2 bits of each byte to $10$; use all remaining bits to fill in the Unicode code point of the character.
- For a one-byte character, set the highest bit to $0$ and the remaining 7 bits to its Unicode code point. ASCII occupies the first 128 Unicode code points, so **UTF-8 is backward-compatible with ASCII**. UTF-8 can therefore decode old ASCII text.
- For an $n$-byte character, where $n > 1$, set the first byte's leading $n$ bits to $1$ and the next bit, $n + 1$, to $0$. Starting with the second byte, set the leading 2 bits of every byte to $10$. Fill the remaining bits with the character's Unicode code point.
The figure below shows the UTF-8 encoding corresponding to "Hello 算法". It can be observed that since the highest $n$ bits are all set to $1$, the system can determine that the character length is $n$ by counting the leading $1$ bits.
The figure below shows UTF-8 for "Hello算法". Since the leading $n$ bits are $1$, the system can determine the character length $n$ by counting the leading $1$ bits.
But why set the highest 2 bits of all other bytes to $10$? In fact, this $10$ can serve as a check symbol. Assuming the system starts parsing text from an incorrect byte, the $10$ at the beginning of the byte can help the system quickly determine an anomaly.
Why do all remaining bytes begin with $10$? This $10$ acts as a check marker. If decoding starts at the wrong byte, the leading $10$ helps the system quickly detect the problem.
The reason for using $10$ as a check symbol is that under UTF-8 encoding rules, it is impossible for a character's highest two bits to be $10$. This conclusion can be proven by contradiction: assuming the highest two bits of a character are $10$, it means the length of the character is $1$, corresponding to ASCII code. However, the highest bit of ASCII code should be $0$, which contradicts the assumption.
The prefix $10$ works as a marker because no character's first byte can begin with $10$ under UTF-8's rules. To see this by contradiction, suppose it did begin with $10$. The single leading one would imply a length of $1$ byte, corresponding to ASCII, but an ASCII byte must begin with $0$, a contradiction.
![UTF-8 encoding example](character_encoding.assets/utf-8_hello_algo.png)
![Example of UTF-8 encoding](character_encoding.assets/utf-8_hello_algo.png)
In addition to UTF-8, common encoding methods also include the following two.
Two other common encodings are:
- **UTF-16 encoding**: Uses 2 or 4 bytes to represent a character. All ASCII characters and commonly used non-English characters are represented with 2 bytes; a few characters need to use 4 bytes. For 2-byte characters, UTF-16 encoding is equal to the Unicode code point.
- **UTF-32 encoding**: Every character uses 4 bytes. This means that UTF-32 takes up more space than UTF-8 and UTF-16, especially for text with a high proportion of ASCII characters.
- **UTF-16**: Uses 2 or 4 bytes per character. ASCII and common non-English characters use 2 bytes; some characters require 4. For a two-byte character, its UTF-16 encoding equals its Unicode code point.
- **UTF-32**: Uses 4 bytes for every character. It therefore takes more space than UTF-8 or UTF-16, especially for text containing mostly ASCII characters.
From the perspective of storage space occupation, using UTF-8 to represent English characters is very efficient because it only requires 1 byte; using UTF-16 encoding for some non-English characters (such as Chinese) will be more efficient because it only requires 2 bytes, while UTF-8 may require 3 bytes.
In terms of storage, UTF-8 is efficient for English characters because each uses only 1 byte. UTF-16 is more efficient for some non-English characters, such as Chinese, using 2 bytes where UTF-8 may require 3.
From a compatibility perspective, UTF-8 has the best universality, and many tools and libraries support UTF-8 first.
In terms of compatibility, UTF-8 is the most widely supported, and many tools and libraries prioritize it.
## Character Encoding in Programming Languages
## Character encoding in programming languages
For many programming languages in the past, strings during program execution used internal encodings such as UTF-16 or UTF-32. Under these representations, we can often treat strings like arrays during processing, and this approach has the following advantages.
Historically, most programming languages have stored strings at runtime using fixed-width encodings such as UTF-16 or UTF-32. Fixed-width encoding lets us treat a string as an array, with the following advantages.
- **Random access**: UTF-16 encoded strings can be easily accessed randomly. UTF-8 is a variable-length encoding. To find the $i$-th character, we need to traverse from the beginning of the string to the $i$-th character, which requires $O(n)$ time.
- **Character counting**: Similar to random access, calculating the length of a UTF-16 encoded string is also an $O(1)$ operation. However, calculating the length of a UTF-8 encoded string requires traversing the entire string.
- **String operations**: Many string operations (such as splitting, joining, inserting, deleting, etc.) on UTF-16 encoded strings are easier to perform. Performing these operations on UTF-8 encoded strings usually requires additional calculations to ensure that invalid UTF-8 encoding is not generated.
- **Random access**: UTF-16 strings support straightforward random access. With variable-length UTF-8, finding the $i$-th character requires traversing from the beginning to the $i$-th character, taking $O(n)$ time.
- **Character counting**: Similarly, finding the length of a UTF-16 string is an $O(1)$ operation, while finding the character count of a UTF-8 string requires traversing the whole string.
- **String operations**: Operations such as splitting, concatenation, insertion, and deletion are easier on UTF-16 strings. With UTF-8, they usually require extra work to avoid producing invalid encodings.
In fact, the design of character encoding schemes for programming languages is a very interesting topic involving many factors.
The design of string representations is an interesting subject involving many factors.
- Java's `String` type uses UTF-16 encoding, with each character occupying 2 bytes. This is because at the beginning of Java language design, people believed that 16 bits were sufficient to represent all possible characters. However, this was an incorrect judgment. Later, the Unicode specification expanded beyond 16 bits, so characters in Java may now be represented by a pair of 16-bit values (called "surrogate pairs").
- The strings of JavaScript and TypeScript use UTF-16 encoding for reasons similar to Java. When Netscape first introduced the JavaScript language in 1995, Unicode was still in its early stages of development, and at that time, using 16-bit encoding was sufficient to represent all Unicode characters.
- C# uses UTF-16 encoding mainly because the .NET platform was designed by Microsoft, and many of Microsoft's technologies (including the Windows operating system) extensively use UTF-16 encoding.
- Java's `String` uses UTF-16, with 2 bytes per character. When Java was designed, 16 bits were thought sufficient for every character. This turned out to be incorrect: Unicode later expanded beyond 16 bits, so a Java character may now require a pair of 16-bit values called a surrogate pair.
- JavaScript and TypeScript use UTF-16 for similar historical reasons. When Netscape introduced JavaScript in 1995, Unicode was still young, and 16 bits could represent all its characters at the time.
- C# uses UTF-16 largely because Microsoft designed .NET, and many Microsoft technologies, including Windows, use UTF-16 extensively.
Due to the underestimation of character quantities by the above programming languages, they had to adopt the "surrogate pair" method to represent Unicode characters with lengths exceeding 16 bits. This is a reluctant compromise. On the one hand, in strings containing surrogate pairs, one character may occupy 2 bytes or 4 bytes, thus losing the advantage of fixed-length encoding. On the other hand, handling surrogate pairs requires additional code, which increases the complexity and difficulty of debugging in programming.
Having underestimated the number of characters, these languages had to adopt surrogate pairs for Unicode characters beyond 16 bits. This was a compromise. A character in such a string may occupy 2 or 4 bytes, losing the benefit of fixed width, and handling surrogate pairs requires additional code, making programming and debugging more complex.
For the above reasons, some programming languages have proposed different encoding schemes.
For these reasons, some languages use different representations.
- Python's `str` uses Unicode encoding and adopts a flexible string representation where the stored character length depends on the largest Unicode code point in the string. If all characters in the string are ASCII characters, each character occupies 1 byte; if there are characters exceeding the ASCII range but all within the Basic Multilingual Plane (BMP), each character occupies 2 bytes; if there are characters exceeding the BMP, each character occupies 4 bytes.
- Go language's `string` type uses UTF-8 encoding internally. Go language also provides the `rune` type, which is used to represent a single Unicode code point.
- Rust language's `str` and `String` types use UTF-8 encoding internally. Rust also provides the `char` type for representing a single Unicode code point.
- Python's `str` uses Unicode with a flexible representation whose character width depends on the largest code point in the string. If all characters are ASCII, each uses 1 byte. If some exceed ASCII but all lie within the Basic Multilingual Plane (BMP), each uses 2 bytes. If any lie outside the BMP, each uses 4 bytes.
- Go's `string` uses UTF-8 internally. Go also provides `rune` to represent a single Unicode code point.
- Rust's `str` and `String` use UTF-8 internally, while `char` represents a single Unicode code point.
It should be noted that the above discussion is about how strings are stored in programming languages, **which is different from how strings are stored in files or transmitted over networks**. In file storage or network transmission, we usually encode strings into UTF-8 format to achieve optimal compatibility and space efficiency.
These descriptions concern string storage within programming languages. **How strings are stored in files or transmitted over a network is a separate question**. For file storage and network transmission, strings are usually encoded as UTF-8 for compatibility and space efficiency.

View File

@@ -1,48 +1,48 @@
# Classification of Data Structures
# Classifying data structures
Common data structures include arrays, linked lists, stacks, queues, hash tables, trees, heaps, and graphs. They can be classified from two dimensions: "logical structure" and "physical structure".
Common data structures include arrays, linked lists, stacks, queues, hash tables, trees, heaps, and graphs. They can be classified by their logical structure and physical structure.
## Logical Structure: Linear and Non-Linear
## Logical structure: linear and nonlinear
**Logical structure reveals the logical relationships between data elements**. In arrays and linked lists, data is arranged in a certain order, embodying linear relationships between elements; while in trees, data is arranged hierarchically from top to bottom, showing parent-descendant relationships; graphs are composed of nodes and edges, reflecting complex network relationships.
**Logical structure describes the relationships between data elements**. Arrays and linked lists arrange data in sequence, expressing linear relationships. Trees arrange data hierarchically from top to bottom, expressing ancestry and descent. Graphs consist of vertices and edges that express complex network relationships.
As shown in the figure below, logical structures can be divided into two major categories: "linear" and "non-linear". Linear structures are more intuitive, indicating that data is linearly arranged in logical relationships; non-linear structures are the opposite, arranged non-linearly.
As shown in the figure below, logical structures fall into two broad categories: linear and nonlinear. A linear structure arranges data in a logical sequence; a nonlinear structure does not.
- **Linear data structures**: Arrays, linked lists, stacks, queues, hash tables, where elements have a one-to-one sequential relationship.
- **Non-linear data structures**: Trees, heaps, graphs, hash tables.
- **Linear data structures**: Arrays, linked lists, stacks, queues, and hash tables. Elements have one-to-one sequential relationships.
- **Nonlinear data structures**: Trees, heaps, graphs, and hash tables.
Non-linear data structures can be further divided into tree structures and network structures.
Nonlinear data structures can be divided further into tree and network structures.
- **Tree structures**: Trees, heaps, hash tables, where elements have a one-to-many relationship.
- **Network structures**: Graphs, where elements have a many-to-many relationship.
- **Tree structures**: Trees, heaps, and hash tables, with one-to-many relationships.
- **Network structures**: Graphs, with many-to-many relationships.
![Linear and non-linear data structures](classification_of_data_structure.assets/classification_logic_structure.png)
![Linear and nonlinear data structures](classification_of_data_structure.assets/classification_logic_structure.png)
## Physical Structure: Contiguous and Dispersed
## Physical structure: contiguous and scattered storage
**When an algorithm program runs, the data being processed is mainly stored in memory**. The figure below shows a computer memory stick, where each black square contains a memory space. We can imagine memory as a huge Excel spreadsheet, where each cell can store a certain amount of data.
**While an algorithm runs, the data it processes is mainly stored in memory**. The figure below shows a memory module, with each black chip containing storage space. We can imagine memory as a huge Excel spreadsheet, where each cell holds a certain amount of data.
**The system accesses data at the target location through memory addresses**. As shown in the figure below, the computer assigns a number to each cell in the spreadsheet according to specific rules, ensuring that each memory space has a unique memory address. With these addresses, the program can access data in memory.
**The system uses memory addresses to access data at particular locations**. As shown in the figure below, the computer assigns each cell a number according to specific rules, giving every memory location a unique address. Programs use these addresses to access data.
![Memory stick, memory space, memory address](classification_of_data_structure.assets/computer_memory_location.png)
![Memory module, storage space, and memory addresses](classification_of_data_structure.assets/computer_memory_location.png)
!!! tip
It should be noted that comparing memory to an Excel spreadsheet is only a simplified analogy. The actual workings of memory are much more complex, involving concepts such as address space, memory management, cache mechanisms, virtual memory, and physical memory.
The Excel spreadsheet analogy is a simplification. Real memory is more complex and involves address spaces, memory management, caching, virtual memory, and physical memory.
Memory is a shared resource for all programs. When a block of memory is occupied by a program, it usually cannot be used by other programs at the same time. **Therefore, in the design of data structures and algorithms, memory resources are an important consideration**. For example, the peak memory occupied by an algorithm should not exceed the remaining free memory of the system; if there is a lack of contiguous large memory blocks, then the data structure chosen must be able to be stored in dispersed memory spaces.
Memory is a resource used by all programs. When a program occupies a region of memory, other programs usually cannot use that region at the same time. **Memory resources are therefore an important consideration when designing data structures and algorithms**. For example, an algorithm's peak memory usage should not exceed the system's available memory. If no large contiguous region is available, the chosen data structure must support scattered storage.
As shown in the figure below, **physical structure reflects the way data is stored in computer memory**. It can be divided into contiguous-space storage (arrays) and dispersed-space storage (linked lists). At a low level, physical structure determines how data is accessed, updated, inserted, and deleted. These two physical structures exhibit complementary characteristics in terms of time efficiency and space efficiency.
As shown in the figure below, **physical structure describes how data is stored in computer memory**: either contiguously (arrays) or in scattered locations (linked lists). It determines how data can be accessed, updated, inserted, and deleted. The two storage forms have complementary strengths in time and space efficiency.
![Contiguous space storage and dispersed space storage](classification_of_data_structure.assets/classification_phisical_structure.png)
![Contiguous and scattered storage](classification_of_data_structure.assets/classification_phisical_structure.png)
It is worth noting that **all data structures are implemented based on arrays, linked lists, or a combination of both**. For example, stacks and queues can be implemented using either arrays or linked lists; while the implementation of hash tables may include both arrays and linked lists.
**All data structures are implemented using arrays, linked lists, or a combination of the two**. For example, stacks and queues can use either arrays or linked lists, while hash tables may use both.
- **Can be implemented based on arrays**: Stacks, queues, hash tables, trees, heaps, graphs, matrices, tensors (arrays with dimensions $\geq 3$), etc.
- **Can be implemented based on linked lists**: Stacks, queues, hash tables, trees, heaps, graphs, etc.
- **Array-based implementations**: Stacks, queues, hash tables, trees, heaps, graphs, matrices, tensors (arrays with dimension $\geq 3$), and more.
- **Linked-list-based implementations**: Stacks, queues, hash tables, trees, heaps, graphs, and more.
After initialization, linked lists can still adjust their length during program execution, so they are also called "dynamic data structures". After initialization, the length of arrays cannot be changed, so they are also called "static data structures". It is worth noting that arrays can change length by reallocating memory, thus retaining a limited degree of flexibility.
A linked list can change length during execution after initialization, so it is called a dynamic data structure. An array's length is fixed after initialization, so it is called a static data structure. However, reallocating memory can change an array's length, providing a degree of dynamic behavior.
!!! tip
If you find it difficult to understand physical structure, it is recommended to read the next chapter first, and then review this section.
If physical structure feels difficult to understand, read the next chapter first and then return to this section.

View File

@@ -1,86 +1,86 @@
# Exercises
## Concept Review
## Check your understanding
### Data Relationships in Everyday Situations
### Relationships between data in everyday situations
Based on the relationships among the data, choose one of "linear structure," "tree structure," and "network structure" for each situation below, and explain why:
For each situation below, choose a linear, tree, or network structure based on the relationships between the data, and explain your choice:
<!-- numbered-subquestions -->
1. Students stand in a line; we consider only each student's immediate neighbors in front of and behind them.
2. A school is organized in levels: "school → grade → class."
3. City roads connect many intersections. One intersection may lead to several others, and the roads may form cycles.
1. Students stand in a line, each concerned only with the people immediately in front of and behind them.
2. A school is organized in a hierarchy: school → grade → class.
3. City roads connect intersections. An intersection can lead to several others, and the roads may form cycles.
??? success "Answer"
??? success "Reference answer"
1. This is a linear structure. Except for the first and last students, each person is adjacent to exactly one person in front and one behind, so the relationships extend along a single line.
1. A linear structure. Apart from the first and last people, each person has exactly one neighbor in front and one behind, forming a line of relationships.
2. This is a tree structure. Each class belongs to one grade, and each grade belongs to the school, so the relationships form levels from top to bottom.
2. A tree structure. Each class belongs to a grade, and each grade belongs to the school, forming a hierarchy from top to bottom.
3. This is a network structure. An intersection can connect to several other intersections, and the routes can form cycles, so they cannot be arranged in a single order or a strict hierarchy.
3. A network structure. An intersection can connect to several others, and routes can form cycles. These relationships cannot be arranged in a single sequence or a strict hierarchy.
To identify a structure, first examine the relationships among the elements rather than how much space it uses in memory.
To identify a structure, first examine the relationships between its elements, rather than how much memory it occupies.
### Storing a Logical Order in Memory
### Storing a logical sequence in memory
Consider two simplified memory layouts for storing the logical order `A → B → C`:
Consider two simplified memory layouts for storing the logical sequence `A → B → C`:
- Layout A: `A, B, C` are stored in memory cells numbered `20, 21, 22`, respectively.
- Layout B: `A, B, C` are stored in memory cells numbered `20, 7, 31`, respectively. `A` records the location of `B`, and `B` records the location of `C`.
- Layout B: `A, B, C` are stored in cells numbered `20, 7, 31`, respectively. `A` records the location of `B`, and `B` records the location of `C`.
<!-- numbered-subquestions -->
1. Which layout uses contiguous-space storage, and which uses dispersed-space storage?
1. Which layout uses contiguous storage, and which uses noncontiguous storage?
2. Which layout is more like an array, and which is more like a linked list?
3. The memory-cell numbers in Layout B are not in increasing order. Why can it still represent the logical order `A → B → C`?
3. The cell numbers in layout B are not in ascending order. Why can it still represent the logical sequence `A → B → C`?
??? success "Answer"
??? success "Reference answer"
1. Layout A uses consecutive memory cells, so it uses contiguous-space storage. The nodes in Layout B are scattered across different locations, so it uses dispersed-space storage.
1. Layout A uses consecutive memory cells, so its storage is contiguous. In layout B, nodes occupy separate locations, so its storage is noncontiguous.
2. Layout A is more like an array, and Layout B is more like a linked list.
2. Layout A is more like an array; layout B is more like a linked list.
3. The logical order is determined by the links recorded between nodes, not by the numerical order of the memory-cell numbers.
The location stored by `A` leads to `B`, and the location stored by `B` then leads to `C`, so `A, B, C` can still be visited in order.
3. The logical order is determined by the links recorded between nodes, not by the numerical order of their memory cell numbers.
The location stored in `A` leads to `B`, and the location stored in `B` leads to `C`, so we can still visit `A, B, C` in sequence.
This also shows that logical structure and physical structure are two different ways of viewing the same data.
This also shows that logical and physical structure are two ways of looking at the same data.
### Data Types and Structures in Homework Records
### Data types and structures in homework records
A study group records, in seating order, whether each of four students submitted their homework:
A study group records whether four students have submitted their homework, in seating order:
`[true, false, true, true]`
<!-- numbered-subquestions -->
1. Which basic data type is suitable for each element?
2. The four elements are arranged in a line by seating order. What logical structure does this use?
3. Suppose the group later records each student's homework score as `[90, 0, 85, 100]`. Does this change the data's "content type" or its "organization"? Explain why.
2. These four elements form a sequence in seating order. What logical structure does this use?
3. If the group later records homework scores instead, as `[90, 0, 85, 100]`, has the type of content changed, or the way it is organized? Explain.
??? success "Answer"
??? success "Reference answer"
1. Each element represents only "yes" or "no," so the Boolean type `bool` is suitable.
1. Each element represents only yes or no, so the Boolean type `bool` is appropriate.
2. The elements are arranged in seating order, forming a linear structure that can be stored in an array.
2. The elements form a linear structure in seating order and can be stored in an array.
3. The content type changes: the elements change from Boolean values to integers. The organization does not change.
The data is still arranged in a line by seating order and can still be stored in an array, which is a linear structure.
3. The content type has changed: the elements are now integers instead of Boolean values. Their organization has not changed.
The data still forms a sequence in seating order and can still use the linear structure of an array.
A basic data type describes "what is stored," while a data structure describes "how the data is organized."
A basic data type describes what is stored; a data structure describes how the data is organized.
## Programming Exercises
## Programming exercises
### Count the 1s in a Binary Representation
### Counting ones in a binary representation
Given a non-negative integer `n`, count the number of 1s in its binary representation.
Given a nonnegative integer `n`, count the ones in its binary representation.
Use bitwise operations. Do not convert the binary representation to a string or use a built-in function that directly counts 1s.
Use bitwise operations. Do not convert the binary representation to a string or use a built-in function that counts the ones directly.
??? tip "Hints"
1. n & 1 extracts the rightmost bit of n, which tells you whether that bit is 1
2. Shifting right by one discards the current rightmost bit; most languages use the operator >>
3. After implementing the method that checks and shifts one bit at a time, observe that n & (n - 1) turns the rightmost 1 in n into 0
1. n & 1 extracts the rightmost bit of n, allowing you to check whether it is 1.
2. Shifting right by one bit discards the current rightmost bit; most languages use the >> operator.
3. After implementing the method that checks each bit and shifts right, observe that n & (n - 1) changes the rightmost 1 in n to 0.
[LeetCode](https://leetcode.com/problems/number-of-1-bits/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }

View File

@@ -1,9 +1,9 @@
# Data Structures
# Data structures
![Data structures](../assets/covers/chapter_data_structure.jpg)
!!! abstract
Data structures are like a sturdy and diverse framework.
It provides a blueprint for the orderly organization of data, upon which algorithms come to life.
Data structures provide a framework that is both sturdy and versatile.
They offer a blueprint for organizing data, a foundation on which algorithms come to life.

View File

@@ -1,24 +1,24 @@
# Number Encoding *
# Number encoding *
!!! tip
In this book, chapters marked with an asterisk * are optional readings. If you are short on time or find them challenging, you may skip these initially and return to them after completing the essential chapters.
Sections marked with * in their titles are optional. If you are short on time or find them difficult, you can skip them initially and return after completing the required sections.
## Sign-Magnitude, 1's Complement, and 2's Complement
## Sign-magnitude, one's complement, and two's complement
In the table from the previous section, we found that all integer types can represent one more negative number than positive numbers. For example, the `byte` range is $[-128, 127]$. This phenomenon is counterintuitive, and its underlying cause lies in sign-magnitude, 1's complement, and 2's complement representations.
The previous table showed that every integer type represents one more negative value than positive value. For example, `byte` ranges over $[-128, 127]$. Understanding this counterintuitive fact requires sign-magnitude, one's complement, and two's complement.
First, it should be noted that **numbers are stored in computers in the form of "2's complement"**. Before analyzing the reasons for this, let's first define these three concepts.
First, **integers are stored in two's complement form**. Before explaining why, let's define the three representations.
- **Sign-magnitude**: We treat the highest bit of the binary representation of a number as the sign bit, where $0$ represents a positive number and $1$ represents a negative number, and the remaining bits represent the value of the number.
- **1's complement**: The 1's complement of a positive number is the same as its sign-magnitude. For a negative number, the 1's complement is obtained by inverting all bits except the sign bit of its sign-magnitude.
- **2's complement**: The 2's complement of a positive number is the same as its sign-magnitude. For a negative number, the 2's complement is obtained by adding $1$ to its 1's complement.
- **Sign-magnitude**: The highest bit is the sign: $0$ for positive and $1$ for negative. The remaining bits represent the magnitude.
- **One's complement**: A positive number has the same representation as sign-magnitude. For a negative number, invert every bit except the sign bit of its sign-magnitude representation.
- **Two's complement**: A positive number again has the same representation as sign-magnitude. For a negative number, add $1$ to its one's complement.
The figure below shows the conversion methods among sign-magnitude, 1's complement, and 2's complement.
The figure below shows how to convert among these representations.
![Conversions among sign-magnitude, 1's complement, and 2's complement](number_encoding.assets/1s_2s_complement.png)
![Converting between sign-magnitude, one's complement, and two's complement](number_encoding.assets/1s_2s_complement.png)
<u>Sign-magnitude</u>, although the most intuitive, has some limitations. On one hand, **the sign-magnitude of negative numbers cannot be directly used in operations**. For example, calculating $1 + (-2)$ in sign-magnitude yields $-3$, which is clearly incorrect.
Although <u>sign-magnitude</u> is intuitive, it has limitations. First, **negative sign-magnitude values cannot be used directly in ordinary binary arithmetic**. For example, directly adding $1 + (-2)$ in this representation gives $-3$, which is clearly wrong.
$$
\begin{aligned}
@@ -29,20 +29,20 @@ $$
\end{aligned}
$$
To solve this problem, computers introduced <u>1's complement</u>. If we first convert sign-magnitude to 1's complement and calculate $1 + (-2)$ in 1's complement, then convert the result back to sign-magnitude, we can obtain the correct result of $-1$.
To address this, computers introduced <u>one's complement</u>. Convert the operands to one's complement, calculate $1 + (-2)$, and convert the result back to sign-magnitude to obtain the correct answer, $-1$.
$$
\begin{aligned}
& 1 + (-2) \newline
& \rightarrow 0000 \; 0001 \; \text{(Sign-magnitude)} + 1000 \; 0010 \; \text{(Sign-magnitude)} \newline
& = 0000 \; 0001 \; \text{(1's complement)} + 1111 \; 1101 \; \text{(1's complement)} \newline
& = 1111 \; 1110 \; \text{(1's complement)} \newline
& = 1000 \; 0001 \; \text{(Sign-magnitude)} \newline
& \rightarrow 0000 \; 0001 \; \text{(sign-magnitude)} + 1000 \; 0010 \; \text{(sign-magnitude)} \newline
& = 0000 \; 0001 \; \text{(one's complement)} + 1111 \; 1101 \; \text{(one's complement)} \newline
& = 1111 \; 1110 \; \text{(one's complement)} \newline
& = 1000 \; 0001 \; \text{(sign-magnitude)} \newline
& \rightarrow -1
\end{aligned}
$$
On the other hand, **the sign-magnitude of the number zero has two representations, $+0$ and $-0$**. This means that the number zero corresponds to two different binary encodings, which may cause ambiguity. For example, in conditional judgments, if we don't distinguish between positive zero and negative zero, it may lead to incorrect judgment results. If we want to handle the ambiguity of positive and negative zero, we need to introduce additional judgment operations, which may reduce the computational efficiency of the computer.
Second, **sign-magnitude has two representations of zero, $+0$ and $-0$**. Two binary encodings for zero can create ambiguity. Conditional checks may be wrong if they do not handle both forms, while special handling requires extra checks that can reduce efficiency.
$$
\begin{aligned}
@@ -51,70 +51,70 @@ $$
\end{aligned}
$$
Like sign-magnitude, 1's complement also has the problem of positive and negative zero ambiguity. Therefore, computers further introduced <u>2's complement</u>. Let's first observe the conversion process of negative zero from sign-magnitude to 1's complement to 2's complement:
One's complement also has positive and negative zero, so computers introduced <u>two's complement</u>. Consider converting negative zero through all three representations:
$$
\begin{aligned}
-0 \rightarrow \; & 1000 \; 0000 \; \text{(Sign-magnitude)} \newline
= \; & 1111 \; 1111 \; \text{(1's complement)} \newline
= 1 \; & 0000 \; 0000 \; \text{(2's complement)} \newline
-0 \rightarrow \; & 1000 \; 0000 \; \text{(sign-magnitude)} \newline
= \; & 1111 \; 1111 \; \text{(one's complement)} \newline
= 1 \; & 0000 \; 0000 \; \text{(two's complement)} \newline
\end{aligned}
$$
Adding $1$ to the 1's complement of negative zero produces a carry, but since the `byte` type has a length of only 8 bits, the $1$ that overflows to the 9th bit is discarded. That is to say, **the 2's complement of negative zero is $0000 \; 0000$, which is the same as the 2's complement of positive zero**. This means that in 2's complement representation, there is only one zero, and the positive and negative zero ambiguity is thus resolved.
Adding $1$ to the one's complement of negative zero produces a carry. A `byte` has only 8 bits, so the $1$ carried into the ninth bit is discarded. **Negative zero's two's complement is therefore $0000 \; 0000$, the same as positive zero**. Two's complement has only one zero, eliminating the ambiguity.
One last question remains: the range of the `byte` type is $[-128, 127]$, so where does the extra negative number $-128$ come from? We notice that all integers in the interval $[-127, +127]$ have corresponding sign-magnitude, 1's complement, and 2's complement, and sign-magnitude and 2's complement can be converted to each other.
One question remains: if `byte` ranges over $[-128, 127]$, where does the extra negative value $-128$ come from? Every integer in $[-127, +127]$ has sign-magnitude, one's complement, and two's complement representations, and its sign-magnitude and two's complement forms can be converted into each other.
However, **the 2's complement $1000 \; 0000$ is an exception, and it does not have a corresponding sign-magnitude**. According to the conversion method, we get that the sign-magnitude of this 2's complement is $0000 \; 0000$. This is clearly contradictory because this sign-magnitude represents the number $0$, and its 2's complement should be itself. The computer specifies that this special 2's complement $1000 \; 0000$ represents $-128$. In fact, the result of calculating $(-1) + (-127)$ in 2's complement is $-128$.
However, **the two's complement value $1000 \; 0000$ is an exception with no corresponding sign-magnitude form**. Applying the conversion gives $0000 \; 0000$, but that represents $0$, whose two's complement should be itself. The special pattern $1000 \; 0000$ is defined to represent $-128$. Indeed, two's complement addition of $(-1) + (-127)$ gives $-128$.
$$
\begin{aligned}
& (-127) + (-1) \newline
& \rightarrow 1111 \; 1111 \; \text{(Sign-magnitude)} + 1000 \; 0001 \; \text{(Sign-magnitude)} \newline
& = 1000 \; 0000 \; \text{(1's complement)} + 1111 \; 1110 \; \text{(1's complement)} \newline
& = 1000 \; 0001 \; \text{(2's complement)} + 1111 \; 1111 \; \text{(2's complement)} \newline
& = 1000 \; 0000 \; \text{(2's complement)} \newline
& \rightarrow 1111 \; 1111 \; \text{(sign-magnitude)} + 1000 \; 0001 \; \text{(sign-magnitude)} \newline
& = 1000 \; 0000 \; \text{(one's complement)} + 1111 \; 1110 \; \text{(one's complement)} \newline
& = 1000 \; 0001 \; \text{(two's complement)} + 1111 \; 1111 \; \text{(two's complement)} \newline
& = 1000 \; 0000 \; \text{(two's complement)} \newline
& \rightarrow -128
\end{aligned}
$$
You may have noticed that all the above calculations are addition operations. This hints at an important fact: **the hardware circuits inside computers are mainly designed based on addition operations**. This is because addition operations are simpler to implement in hardware compared to other operations (such as multiplication, division, and subtraction), easier to parallelize, and have faster operation speeds.
All the calculations above use addition. This points to an important fact: **computer arithmetic circuits are largely built around addition**. Compared with operations such as multiplication, division, and subtraction, addition is simpler to implement in hardware, easier to parallelize, and faster.
Please note that this does not mean that computers can only perform addition. **By combining addition with some basic logical operations, computers can implement various other mathematical operations**. For example, calculating the subtraction $a - b$ can be converted to calculating the addition $a + (-b)$; calculating multiplication and division can be converted to calculating multiple additions or subtractions.
This does not mean computers can only add. **Combining addition with basic logical operations makes other arithmetic possible**. For example, subtraction $a - b$ becomes addition $a + (-b)$, while multiplication and division can be expressed as repeated additions or subtractions.
We can now summarize why computers use 2's complement: with 2's complement representation, computers can use the same circuits and operations to handle the addition of positive and negative numbers, without designing special hardware circuits for subtraction or separately handling the ambiguity of positive and negative zero. This greatly simplifies hardware design and improves efficiency.
We can now summarize why computers use two's complement. It lets the same circuitry and operations handle both positive and negative addition, without dedicated subtraction circuitry or special handling for positive and negative zero. This simplifies hardware and improves efficiency.
The design of 2's complement is very ingenious. Due to space limitations, we will stop here. Interested readers are encouraged to explore further.
Two's complement is an elegant design. Space limits our discussion here, but interested readers are encouraged to explore it further.
## Floating-Point Number Encoding
## Floating-point encoding
Careful readers may have noticed: `int` and `float` have the same length, both are 4 bytes, but why does `float` have a much larger range than `int`? This is very counterintuitive because it stands to reason that `float` needs to represent decimals, so the range should be smaller.
Both `int` and `float` occupy 4 bytes, yet `float` has a much wider range. This seems surprising: since `float` also represents fractions, should its range not be smaller?
In fact, **this is because floating-point number `float` uses a different representation method**. Let's denote a 32-bit binary number as:
**The reason is that `float` uses a different representation**. Write a 32-bit binary number as:
$$
b_{31} b_{30} b_{29} \ldots b_2 b_1 b_0
$$
According to the IEEE 754 standard, a 32-bit `float` consists of the following three parts.
Under IEEE 754, a 32-bit `float` has three parts.
- Sign bit $\mathrm{S}$: occupies 1 bit, corresponding to $b_{31}$.
- Exponent bit $\mathrm{E}$: occupies 8 bits, corresponding to $b_{30} b_{29} \ldots b_{23}$.
- Fraction bit $\mathrm{N}$: occupies 23 bits, corresponding to $b_{22} b_{21} \ldots b_0$.
- Sign $\mathrm{S}$: 1 bit, corresponding to $b_{31}$.
- Exponent $\mathrm{E}$: 8 bits, corresponding to $b_{30} b_{29} \ldots b_{23}$.
- Fraction $\mathrm{N}$: 23 bits, corresponding to $b_{22} b_{21} \ldots b_0$.
The calculation method for the value corresponding to the binary `float` is:
The value represented by the binary `float` is:
$$
\text {val} = (-1)^{b_{31}} \times 2^{\left(b_{30} b_{29} \ldots b_{23}\right)_2-127} \times\left(1 . b_{22} b_{21} \ldots b_0\right)_2
$$
Converted to decimal, the calculation formula is:
In decimal notation, this becomes:
$$
\text {val}=(-1)^{\mathrm{S}} \times 2^{\mathrm{E} -127} \times (1 + \mathrm{N})
$$
The range of each component is:
The components have these ranges:
$$
\begin{aligned}
@@ -123,28 +123,28 @@ $$
\end{aligned}
$$
![Calculation example of float under IEEE 754 standard](number_encoding.assets/ieee_754_float.png)
![Example of an IEEE 754 float calculation](number_encoding.assets/ieee_754_float.png)
Observing the figure above, given example data $\mathrm{S} = 0$, $\mathrm{E} = 124$, $\mathrm{N} = 2^{-2} + 2^{-3} = 0.375$, we have:
In the figure above, $\mathrm{S} = 0$, $\mathrm{E} = 124$, and $\mathrm{N} = 2^{-2} + 2^{-3} = 0.375$, giving:
$$
\text { val } = (-1)^0 \times 2^{124 - 127} \times (1 + 0.375) = 0.171875
$$
Now we can answer the initial question: **the representation of `float` includes an exponent bit, resulting in a range far greater than `int`**. According to the above calculation, the maximum positive number that `float` can represent is $2^{254 - 127} \times (2 - 2^{-23}) \approx 3.4 \times 10^{38}$, and the minimum negative number can be obtained by switching the sign bit.
We can now answer the original question: **the exponent gives `float` a much wider range than `int`**. The largest positive `float` is $2^{254 - 127} \times (2 - 2^{-23}) \approx 3.4 \times 10^{38}$; changing the sign bit gives the most negative value.
**Although floating-point number `float` expands the range, its side effect is sacrificing precision**. The integer type `int` uses all 32 bits to represent numbers, and the numbers are evenly distributed; however, due to the existence of the exponent bit, the larger the value of floating-point number `float`, the larger the difference between two adjacent numbers tends to be.
**The wider range of `float` comes at the cost of precision**. An `int` uses all 32 bits to represent evenly spaced integer values. Because `float` includes an exponent, the gap between adjacent representable values tends to grow as their magnitude increases.
As shown in the table below, exponent bits $\mathrm{E} = 0$ and $\mathrm{E} = 255$ have special meanings, **used to represent zero, infinity, $\mathrm{NaN}$, etc.**
As shown in the table below, exponent values $\mathrm{E} = 0$ and $\mathrm{E} = 255$ have special meanings, **representing zero, infinity, and $\mathrm{NaN}$, among other values**.
<p align="center"> Table <id> &nbsp; Meaning of exponent bits </p>
<p align="center"> Table <id> &nbsp; Meanings of exponent values </p>
| Exponent Bit E | Fraction Bit $\mathrm{N} = 0$ | Fraction Bit $\mathrm{N} \ne 0$ | Calculation Formula |
| ------------------ | ----------------------------- | ------------------------------- | ---------------------------------------------------------------------- |
| $0$ | $\pm 0$ | Subnormal Number | $(-1)^{\mathrm{S}} \times 2^{-126} \times (0.\mathrm{N})$ |
| $1, 2, \dots, 254$ | Normal Number | Normal Number | $(-1)^{\mathrm{S}} \times 2^{(\mathrm{E} -127)} \times (1.\mathrm{N})$ |
| $255$ | $\pm \infty$ | $\mathrm{NaN}$ | |
| Exponent E | Fraction $\mathrm{N} = 0$ | Fraction $\mathrm{N} \ne 0$ | Formula |
| ------------------ | ----------------------- | ------------------------- | ---------------------------------------------------------------------- |
| $0$ | $\pm 0$ | Subnormal number | $(-1)^{\mathrm{S}} \times 2^{-126} \times (0.\mathrm{N})$ |
| $1, 2, \dots, 254$ | Normal number | Normal number | $(-1)^{\mathrm{S}} \times 2^{(\mathrm{E} -127)} \times (1.\mathrm{N})$ |
| $255$ | $\pm \infty$ | $\mathrm{NaN}$ | |
It is worth noting that subnormal numbers significantly improve the precision of floating-point numbers. The smallest positive normal number is $2^{-126}$, and the smallest positive subnormal number is $2^{-126} \times 2^{-23}$.
Subnormal numbers substantially improve precision near zero. The smallest positive normal number is $2^{-126}$, and the smallest positive subnormal number is $2^{-126} \times 2^{-23}$.
Double-precision `double` also uses a representation method similar to `float`, which will not be elaborated here.
Double-precision `double` uses a similar representation, which we will not detail here.

View File

@@ -1,66 +1,66 @@
# Summary
### Key Review
### Key takeaways
- Data structures can be classified from two perspectives: logical structure and physical structure. Logical structure describes the logical relationships between data elements, while physical structure describes how data is stored in computer memory.
- Common logical structures include linear, tree-like, and network structures. We typically classify data structures as linear (arrays, linked lists, stacks, queues) and non-linear (trees, graphs, heaps) based on their logical structure. The implementation of hash tables may involve both linear and non-linear data structures.
- When a program runs, data is stored in computer memory. Each memory space has a corresponding memory address, and the program accesses data through these memory addresses.
- Physical structures are primarily divided into contiguous space storage (arrays) and dispersed space storage (linked lists). All data structures are implemented using arrays, linked lists, or a combination of both.
- Basic data types in computers include integers `byte`, `short`, `int`, `long`, floating-point numbers `float`, `double`, characters `char`, and booleans `bool`. Their value ranges depend on the size of space they occupy and their representation method.
- Sign-magnitude, 1's complement, and 2's complement are three methods for encoding numbers in computers, and they can be converted into each other. The most significant bit of sign-magnitude is the sign bit, and the remaining bits represent the value of the number.
- Integers are stored in computers in 2's complement form. Under 2's complement representation, computers can treat the addition of positive and negative numbers uniformly, without needing to design special hardware circuits for subtraction, and there is no ambiguity of positive and negative zero.
- The encoding of floating-point numbers consists of 1 sign bit, 8 exponent bits, and 23 fraction bits. Due to the exponent bits, the range of floating-point numbers is much larger than that of integers, at the cost of sacrificing precision.
- ASCII is the earliest English character set, with a length of 1 byte, containing a total of 128 characters. GBK is a commonly used Chinese character set, containing over 20,000 Chinese characters. Unicode is committed to providing a complete character set standard, collecting characters from various languages around the world, thereby solving the garbled text problem caused by inconsistent character encoding methods.
- UTF-8 is the most popular Unicode encoding method and has excellent compatibility. It is a variable-length encoding method with good scalability, effectively improving storage space efficiency. UTF-16 and UTF-32 are common Unicode encoding methods. When encoding Chinese characters, UTF-16 occupies less space than UTF-8. Programming languages such as Java and C# use UTF-16 encoding by default.
- Data structures can be classified by logical and physical structure. Logical structure describes relationships between data elements, while physical structure describes how data is stored in memory.
- Common logical structures are linear, tree, and network structures. We usually classify data structures as linear (arrays, linked lists, stacks, queues) or nonlinear (trees, graphs, heaps). A hash table implementation may contain both linear and nonlinear structures.
- During execution, data resides in computer memory. Each location has a memory address, which programs use to access its data.
- The two main physical structures are contiguous storage (arrays) and scattered storage (linked lists). All data structures are implemented using arrays, linked lists, or both.
- Basic data types include integers (`byte`, `short`, `int`, `long`), floating-point numbers (`float`, `double`), characters (`char`), and Booleans (`bool`). Their value ranges depend on storage size and representation.
- Sign-magnitude, one's complement, and two's complement are three ways to encode numbers, and can be converted into one another. In sign-magnitude representation, the highest bit is the sign and the remaining bits give the magnitude.
- Integers are stored in two's complement. This lets the computer handle positive and negative addition uniformly, avoids separate hardware circuitry for subtraction, and eliminates the ambiguity of positive and negative zero.
- A floating-point encoding consists of 1 sign bit, 8 exponent bits, and 23 fraction bits. The exponent provides a much wider range than integers, at the cost of precision.
- ASCII was the earliest English character set. It uses 1 byte and contains 128 characters. GBK is a common Chinese character set with over 20,000 Chinese characters. Unicode aims to provide a comprehensive character standard for the world's languages, avoiding garbled text caused by incompatible encodings.
- UTF-8 is the most popular Unicode encoding and is widely compatible. Its variable length makes it extensible and space-efficient. UTF-16 and UTF-32 use fixed lengths. For Chinese text, UTF-16 uses less space than UTF-8. Languages such as Java and C# use UTF-16 by default.
### Q & A
**Q**: Why do hash tables contain both linear and non-linear data structures?
**Q**: Why can a hash table contain both linear and nonlinear data structures?
The underlying structure of a hash table is an array. To resolve hash collisions, we may use "chaining" (discussed in the subsequent "Hash Collision" section): each bucket in the array points to a linked list, which may be converted to a tree (usually a red-black tree) when the list length exceeds a certain threshold.
A hash table is built on an array. To handle hash collisions, it may use separate chaining, discussed later in the Hash collisions section: each array bucket points to a linked list, which may be converted to a tree (usually a red-black tree) if it grows beyond a threshold.
From a storage perspective, the underlying structure of a hash table is an array, where each bucket slot may contain a value, a linked list, or a tree. Therefore, hash tables may contain both linear data structures (arrays, linked lists) and non-linear data structures (trees).
From a storage perspective, each bucket in the underlying array may contain a value, a linked list, or a tree. A hash table may therefore contain both linear structures (arrays and linked lists) and nonlinear structures (trees).
**Q**: Is the length of the `char` type 1 byte?
**Q**: Does `char` occupy 1 byte?
The length of the `char` type is determined by the encoding method used by the programming language. For example, Java, JavaScript, TypeScript, and C# all use UTF-16 encoding (to store Unicode code points), so the `char` type has a length of 2 bytes.
The size of `char` depends on the programming language's encoding. For example, Java, JavaScript, TypeScript, and C# use UTF-16 to store Unicode code points, so their `char` type occupies 2 bytes.
**Q**: Is there ambiguity in referring to array-based data structures as "static data structures"? Stacks can also perform "dynamic" operations such as push and pop.
**Q**: Is calling array-based structures static misleading? A stack supports dynamic operations such as pushing and popping.
Stacks can indeed implement dynamic data operations, but the data structure is still "static" (fixed length). Although array-based data structures can dynamically add or remove elements, their capacity is fixed. If the data volume exceeds the pre-allocated size, a new larger array needs to be created, and the contents of the old array must be copied to the new array.
A stack does support dynamic data operations, but its underlying structure remains static in length. Although array-based structures can add and remove elements dynamically, their capacity is fixed. When the data exceeds the allocated capacity, a larger array must be created and the old contents copied into it.
**Q**: When constructing a stack (queue), its size is not specified. Why are they "static data structures"?
**Q**: When we create a stack or queue without specifying its size, why is it still called a static data structure?
In high-level programming languages, we do not need to manually specify the initial capacity of a stack (queue); the class handles this automatically. For example, the initial capacity of Java's `ArrayList` is typically 10. Additionally, the expansion operation is also automatically implemented. See the subsequent "List" section for details.
In high-level languages, the class automatically chooses an initial capacity for a stack or queue. For example, Java's `ArrayList` typically starts with a capacity of 10. Resizing is also automatic; see the later section on lists.
**Q**: The method of converting sign-magnitude to 2's complement is "first negate then add 1". So converting 2's complement to sign-magnitude should be the inverse operation "first subtract 1 then negate". However, 2's complement can also be converted to sign-magnitude through "first negate then add 1". Why is this?
**Q**: Converting sign-magnitude to two's complement uses "invert, then add 1". Its inverse should be "subtract 1, then invert", so why does "invert, then add 1" also work in the reverse direction?
This is because the mutual conversion between sign-magnitude and 2's complement is actually the process of computing the "complement". Let us first define the complement: assuming $a + b = c$, then we say that $a$ is the complement of $b$ to $c$, and conversely, $b$ is the complement of $a$ to $c$.
These conversions are really computations of a complement. If $a + b = c$, we call $a$ the complement of $b$ with respect to $c$, and conversely $b$ the complement of $a$ with respect to $c$.
Given an $n = 4$ bit binary number $0010$, if we treat this number as sign-magnitude (ignoring the sign bit), then its 2's complement can be obtained through "first negate then add 1":
Consider the $n = 4$-bit binary number $0010$. Treating it as sign-magnitude and disregarding the sign bit, we obtain its two's complement by inverting and adding 1:
$$
0010 \rightarrow 1101 \rightarrow 1110
$$
We find that the sum of sign-magnitude and 2's complement is $0010 + 1110 = 10000$, which means the 2's complement $1110$ is the "complement" of sign-magnitude $0010$ to $10000$. **This means the above "first negate then add 1" is actually the process of computing the complement to $10000$**.
The two representations sum to $0010 + 1110 = 10000$. Thus, $1110$ is the complement of $0010$ with respect to $10000$. **The "invert, then add 1" operation computes the complement with respect to $10000$**.
So, what is the "complement" of 2's complement $1110$ to $10000$? We can still use "first negate then add 1" to obtain it:
What is the complement of $1110$ with respect to $10000$? We can again invert and add 1:
$$
1110 \rightarrow 0001 \rightarrow 0010
$$
In other words, sign-magnitude and 2's complement are each other's "complement" to $10000$, so "sign-magnitude to 2's complement" and "2's complement to sign-magnitude" can be implemented using the same operation (first negate then add 1).
The two representations are complements of each other with respect to $10000$, so conversion in either direction can use the same operation: invert, then add 1.
Of course, we can also use the inverse operation to find the sign-magnitude of 2's complement $1110$, that is, "first subtract 1 then negate":
Of course, we can also recover the sign-magnitude form of $1110$ by the inverse operation: subtract 1, then invert.
$$
1110 \rightarrow 1101 \rightarrow 0010
$$
In summary, both "first negate then add 1" and "first subtract 1 then negate" are computing the complement to $10000$, and they are equivalent.
Both "invert, then add 1" and "subtract 1, then invert" compute the complement with respect to $10000$, so they are equivalent.
Essentially, the "negate" operation is actually finding the complement to $1111$ (because "sign-magnitude + 1's complement = 1111" always holds); and adding 1 to the 1's complement yields the 2's complement, which is the complement to $10000$.
In essence, inverting computes the complement with respect to $1111$, since `sign-magnitude + one's complement = 1111`. Adding 1 to the one's complement then gives the complement with respect to $10000$.
The above uses $n = 4$ as an example, and it can be generalized to binary numbers of any number of bits.
The example uses $n = 4$, but the reasoning extends to binary numbers of any bit width.