VOOZH about

URL: https://dev.to/alexandruv156/math-vs-strings-two-ways-to-manipulate-digits-in-c-geb

⇱ 🚀 Math vs. Strings: Two Ways to Manipulate Digits in C++ - DEV Community


In programming, there’s rarely just one way to solve a problem. In this article, we’ll take a classic coding challenge—replacing even digits in a number with 1—and tackle it using two completely different paradigms: pure mathematical logic and modern string manipulation.

Along the way, we’ll explore how to handle tricky edge cases (like 0 and negative numbers) and highlight a common, dangerous C++ rookie mistake: accidentally destroying your variables inside a loop. Whether you are looking for raw performance or clean, readable code, this quick guide has got you covered!



#include <iostream>
#include <string>

using namespace std;

int main()
{
 int number;
 int number_copy;
 int nt = 0; // Stores the result for the first method

 cout << "Enter your number: ";
 cin >> number;

 // --- EDGE CASE HANDLING ---
 // Rule 1: We only accept positive numbers for this algorithm
 if (number < 0) {
 cout << "Please enter a positive number!" << endl;
 return 0;
 }

 // Rule 2: Handing zero separately because it's an even number 
 // and mathematical division loops won't process it.
 if (number == 0) {
 cout << "The changed number for the first method is: 1" << endl;
 cout << "The changed number for the second method is: 1" << endl;
 return 0;
 }
 else {
 // CRITICAL STEP: Back up the original number.
 // The while loop below will destroy the 'number' variable (reducing it to 0).
 number_copy = number;

 long long p = 1; // Base 10 multiplier to reconstruct the number in the correct order

 // --- METHOD 1: THE MATHEMATICAL APPROACH ---
 while (number != 0) {
 int l = number % 10; // Extract the last digit

 // Check if the digit is odd
 if (l % 2 != 0) {
 nt = nt + l * p; // Keep the odd digit as it is
 }
 else {
 nt = nt + 1 * p; // Replace the even digit with 1
 }

 p = p * 10; // Move to the next decimal place (units, tens, hundreds...)
 number = number / 10; // Remove the last digit from the number
 }
 }
 cout << "The changed number for the first method is: " << nt << '\n';

 // --- METHOD 2: THE STRING MANIPULATION APPROACH ---
 // We use 'number_copy' because 'number' is now 0.
 string numberStr = to_string(number_copy); // Convert the integer to a string

 // Loop through each character of the string
 for (int i = 0; i < numberStr.length(); i++) {
 // Check if the current character represents an even digit
 if (numberStr[i] == '0' || numberStr[i] == '2' || numberStr[i] == '4' || numberStr[i] == '6' || numberStr[i] == '8') {
 numberStr[i] = '1'; // Replace the character with '1'
 }
 }

 // Convert the modified string back into a 64-bit integer (long long) to prevent overflow
 long long nt2 = stoll(numberStr);
 cout << "The changed number for the second method is: " << nt2 << endl;

 return 0;
}