I tried to make a Python program that removes specific digit from a number, example a = 12025 k = 2 result is 105, however none of the guides helped me do that, can anybody help me with that?
CodePudding user response:
Conversion to string does not seem elegant. As pseudo-code:
number without digit (number, digit)
if number == digit
0
else if number < 10
number
else if number % 10 == digit
number without digit (number / 10, digit)
else
number without digit (number / 10, digit) * 10 (number % 10)
Where /
is integer division, truncating the remainder, and %
is the modulo, remainder.
So it is a matter of recursion.
CodePudding user response:
You have to convert into str
type, then remove the occurrencies, and go back to int
int(str(a).replace(str(k),''))
CodePudding user response:
a = 12025
k = 2
print(int(str(a).replace(str(k), '')))
CodePudding user response:
If you want to use math rather than converting to and from string you can do
a = 12025
k = 2
result = 0
exp = 0
while a:
a, remainder = divmod(a, 10)
if remainder != k:
result = result 10**exp * remainder
exp = 1