🚀 C++ Programming Lesson 13: Digit Separation and Reversal Techniques — Mastering the “Deconstruction Magic” of Integers

📚 Course Navigation
1、🤔 Why Learn Digit Manipulation Techniques? (Scenarios of Digit Processing in Life)2、🌟 Digit Separation: Breaking Multi-digit Numbers into Single Digits (Core Method: Modulus + Integer Division)3、⚡ Digit Reversal: Turning Integers “Upside Down” (Core Logic: Concatenating the Last Digit)4、🧪 Practical Case: Solving Real Digit Problems (From Basics to Comprehensive Applications)5、⚠️ Common Mistakes and Pitfall Avoidance Techniques (Avoiding Logical Flaws in Digit Processing)6、📢 Next Lesson Preview: Introduction to Arrays (A New Way to Store Data in Batches)
1. 🤔 Why Learn Digit Manipulation Techniques? — Scenarios of Digits in Life
We encounter various integers every day, such as phone numbers, verification codes, and ranking scores. Often, we need to “break and combine” these numbers:
- 📱 Verification Code Check: Upon receiving a 6-digit verification code “123456”, we need to calculate the sum of each digit (1+2+3+4+5+6) to determine if it meets security rules;
- 🔢 Palindrome Check: To determine if “12321” is a palindrome (reads the same forwards and backwards), we first need to reverse the number to “12321” and then compare;
- 📊 Score Statistics: Given a student ID “20240512”, we need to extract the grade (2024), class (05), and student number (12) to separately calculate scores for different classes.
These scenarios require “digit separation” or “digit reversal” techniques, which are fundamental for handling integers in C++. Mastering these techniques will enable programs to easily tackle various digit-related problems.

2. 🌟 Digit Separation: Breaking Multi-digit Numbers into Single Digits
The core of digit separation is:using “modulus (%10)” to obtain the last digit and “integer division (/10)” to remove the last digit, repeating these two steps until the original number becomes 0, allowing us to sequentially extract all single digits (note: the order of extraction is “from last to first”).
(1) Core Principle Demonstration (Using the Number “123” as an Example)
|
Step |
Original Number (num) |
Modulus Operation (num%10) → Extracted Digit |
Integer Division (num/10) → New Number |
|
1 |
123 |
123%10 = 3 (Extracted Last Digit “3”) |
123/10 = 12 (Removed Last Digit) |
|
2 |
12 |
12%10 = 2 (Extracted Middle Digit “2”) |
12/10 = 1 (Removed Last Digit) |
|
3 |
1 |
1%10 = 1 (Extracted First Digit “1”) |
1/10 = 0 (Digit Processing Complete) |
The final order of extracted digits: 3 → 2 → 1 (If you want to output in the order “1→2→3”, you can store them first and then print in reverse).
(2) Code Implementation: Separate Digits and Print
Requirement: Allow the user to input a multi-digit number and print each digit sequentially (from last to first).
#include <iostream>using namespace std;int main() {int num; cout << "请输入一个多位数:"; cin >> num;// Handle special case: directly print if input is 0if (num == 0) { cout << "拆出的数字:0" << endl; return 0; } cout << "拆出的数字(从最后一位到第一位):";// while loop: continue separating as long as num is not 0while (num != 0) {int lastDigit = num % 10; // Get last digit cout << lastDigit << " "; // Print extracted digit num = num / 10; // Remove last digit, update num }return 0;}
Running Scenario:
- User inputs “4567” → Outputs “拆出的数字(从最后一位到第一位):7 6 5 4 “;
- User inputs “0” → Outputs “拆出的数字:0” (avoiding loop not executing).
(3) Advanced Application: Calculate the Sum of Digits of a Multi-digit Number
Requirement: While separating digits, calculate the sum of all digits (for example, the sum of “123” is 1+2+3=6).
#include <iostream>using namespace std;int main() {int num, sum = 0; // sum stores the sum of digits, initialized to 0 cout << "请输入一个多位数:"; cin >> num;// Handle negative numbers: convert to positive (e.g., -123 to 123, does not affect the sum of digits)if (num < 0) { num = -num; }// Separate digits and accumulate while (num != 0) { sum += num % 10; // Add last digit to sum num = num / 10; // Remove last digit } cout << "这个数字各位之和是:" << sum << endl; return 0;}
Running Scenario:
- User inputs “-789” → Outputs “这个数字各位之和是:24” (7+8+9=24);
- User inputs “1024” → Outputs “这个数字各位之和是:7” (1+0+2+4=7).
3. ⚡ Digit Reversal: Turning Integers “Upside Down”
The core of digit reversal is:each time using “modulus (%10)” to get the last digit of the original number, then using “new number = new number * 10 + last digit” to append it to the end of the new number, while using “integer division (/10)” to remove the last digit of the original number, repeating the operation until the original number is 0, the new number is the reversed result.
(1) Core Principle Demonstration (Using the Number “123” as an Example)
|
Step |
Original Number (num) |
Modulus Operation (num%10) Last Digit |
New Number (reverseNum) Calculation |
Integer Division (num/10) New Number |
|
1 |
123 |
123%10 = 3 |
0*10 + 3 = 3 |
123/10 = 12 |
|
2 |
12 |
12%10 = 2 |
3*10 + 2 = 32 |
12/10 = 1 |
|
3 |
1 |
1%10 = 1 |
32*10 + 1 = 321 |
1/10 = 0 |
The final reversed number: 321 (original number 123 → reversed 321).
(2) Code Implementation: Reverse a Number and Output
Requirement: Allow the user to input an integer and output its reversed result (handling positive numbers, negative numbers, and cases with trailing zeros, such as “120” which reverses to “21”).
#include <iostream>using namespace std;int main() {int num, reverseNum = 0; // reverseNum stores the reversed number, initialized to 0 cout << "请输入一个整数:"; cin >> num;// Handle negative numbers: first record the sign, then convert to positive processingint sign = 1; // 1 indicates positive, -1 indicates negativeif (num < 0) { sign = -1; num = -num; }// while loop: reverse the number while (num != 0) {int lastDigit = num % 10; // Get last digit reverseNum = reverseNum * 10 + lastDigit; // Append to new number num = num / 10; // Remove last digit }// Restore sign (if the original number is negative) reverseNum *= sign; cout << "反转后的数字是:" << reverseNum << endl; return 0;}
Running Scenario:
- User inputs “123” → Outputs “反转后的数字是:321”;
- User inputs “-456” → Outputs “反转后的数字是:-654”;
- User inputs “120” → Outputs “反转后的数字是:21” (trailing 0 is automatically removed).
(3) Advanced Application: Palindrome Check
A palindrome is a number that reads the same forwards and backwards (e.g., 121, 1331, 1221). The method to check is:reverse the number and compare it with the original number; if they are equal, it is a palindrome.
#include <iostream>using namespace std;int main() { int num, originalNum, reverseNum = 0; cout << "请输入一个整数,判断是否为回文数:"; cin >> num; originalNum = num; // Save original number for later comparison// Handle negative numbers: negative numbers cannot be palindromes (e.g., -121 reversed is -121, but the sign causes "-121" ≠ "121-") if (num < 0) { cout << num << " 不是回文数" << endl; return 0; }// Reverse the number while (num != 0) { reverseNum = reverseNum * 10 + num % 10; num = num / 10; }// Compare original number and reversed number if (originalNum == reverseNum) { cout << originalNum << " 是回文数" << endl; } else { cout << originalNum << " 不是回文数" << endl; } return 0;}
4. 🧪 Comprehensive Practical Case: Separate and Count Even Digits
Requirement: Allow the user to input a multi-digit number, separate each digit, and count the number of even digits (for example, in “123456”, the even digits are 2, 4, and 6, totaling 3).
#include <iostream>using namespace std;int main() { int num, evenCount = 0; // evenCount counts the number of even digits, initialized to 0 cout << "请输入一个多位数:"; cin >> num;// Handle 0: 0 is even, count it directly if (num == 0) { cout << "数字中偶数的个数:1" << endl; return 0; }// Handle negative numbers: convert to positive if (num < 0) { num = -num; } cout << "分离出的数字:"; while (num != 0) { int lastDigit = num % 10; cout << lastDigit << " "; // Check if it is even (divisible by 2) if (lastDigit % 2 == 0) { evenCount++; } num = num / 10; } cout << "\n数字中偶数的个数:" << evenCount << endl; return 0;}
Running Scenario:
- User inputs “789012” → Outputs “分离出的数字:2 1 0 9 8 7 数字中偶数的个数:3” (even digits are 2, 0, 8);
- User inputs “-1357” → Outputs “分离出的数字:7 5 3 1 数字中偶数的个数:0”.
5. ⚠️ Common Mistakes and Pitfall Avoidance Techniques
Mistake 1: Not Handling the “Input is 0” Case, Leading to Loop Not Executing
For example, during digit separation, if the user inputs 0, the while(num != 0) condition is not satisfied, and the loop does not execute, resulting in no output:
// Error: No output when input is 0while (num != 0) { cout << num % 10 << " "; num /= 10;}
✅ Correct: Check if num is 0 in advance and handle it separately:
if (num == 0) { cout << 0 << endl; return 0;}
Mistake 2: When Handling Negative Numbers, Not Converting to Positive First, Leading to Abnormal Modulus Results
For example, inputting -123, -123%10 results in -3 (which may vary by compiler), affecting subsequent processing:
// Error: Directly taking modulus of negative number may yield negative resultint lastDigit = num % 10; // when num=-123, lastDigit=-3
✅ Correct: First record the sign, then convert num to positive for processing:
int sign = 1;if (num < 0) { sign = -1; num = -num; // Convert to positive 123}
Mistake 3: Not Considering “Integer Overflow” When Reversing Numbers
For example, inputting “1234567899”, reversing it results in “9987654321”, which exceeds the maximum value of int type (about 2.1 billion), leading to incorrect results:
// Risk: reverseNum may overflow when input is too largeint reverseNum = 0;reverseNum = reverseNum * 10 + lastDigit;
✅ Correct: Use long long type to store the reversed number (which has a larger range):
long long reverseNum = 0; // Change to long long to avoid overflow errors
Mistake 4: When Judging Palindromes, Not Excluding Negative Numbers, Leading to Misjudgment
For example, inputting -121, reversing it results in -121, and originalNum == reverseNum holds true, but -121 is not a palindrome (textually “-121” ≠ “121-“):
// Error: Incorrectly considers -121 as a palindromeif (originalNum == reverseNum) { cout << "是回文数";}
✅ Correct: Check in advance, directly determine negative numbers as non-palindromes:
if (num < 0) { cout << "不是回文数" << endl; return 0;}
6. 📢 Next Lesson Preview: Introduction to Arrays (A New Way to Store Data in Batches)
In this lesson, we learned digit separation and reversal, which can handle the “breaking and combining” of a single integer. However, if we need to process “a set of data” (such as the scores of 10 students or the prices of 5 products), using a single variable for storage can be cumbersome (requiring definitions like score1, score2…score10).
In the next lesson, we will learn aboutarrays — they are “containers for batch data storage” that allow you to store multiple data of the same type with one name (for example, int score[10] can store the scores of 10 students, and you can access each score through score[0], score[1]).
Once you master arrays, you will easily implement functions like “calculating the average score of 10 scores” and “finding the lowest price among 5 products” for batch data processing. Looking forward to exploring the usage of arrays together in the next lesson! 😉
