remove digit from number c++
#include <iostream>
#include <string>
using namespace std;
int removeDigit(int number, int digitToRemove) {
string numberString = to_string(number);
string newNumberString = "";
for (char digit : numberString) {
if (digit != (char)(digitToRemove + '0')) {
newNumberString += digit;
}
}
return stoi(newNumberString);
}
int main() {
int number = 12345;
int digitToRemove = 3;
int newNumber = removeDigit(number, digitToRemove);
cout << "Original number: " << number << endl;
cout << "Number with digit " << digitToRemove << " removed: " << newNumber << endl;
return 0;
}
Explanation:
- We include the necessary libraries for input/output and string manipulation.
- We declare a function named removeDigit
that takes two parameters: number
and digitToRemove
.
- Inside the removeDigit
function, we convert the number
to a string using to_string
.
- We initialize an empty string newNumberString
to store the modified number without the specified digit.
- We iterate through each character of the numberString
and check if it is equal to the digitToRemove
. If not, we append it to newNumberString
.
- After the loop, we convert newNumberString
back to an integer using stoi
and return it.
- In the main
function, we define an example number
and digitToRemove
.
- We call the removeDigit
function with these parameters and store the result in newNumber
.
- Finally, we output the original number and the modified number after removing the specified digit using cout
.