For this assignment, I am tasked to:
- Input a number
- Remove even digits from the given number without changing the order of the digits
For example: 123407 will print 137
If a number starts with 246 then it prints 0.
I am not allowed to use strings, lists, functions, packages, recursion, ..., only mathematical operations.
Here is my code so far:
POSITION = 1 # give the digit position of the number
OUTPUT = 0 # printing the output of the result
enterNum = int(input('Enter a Number')) # user inputs a number
while enterNum != 0:
digit = enterNum % 10 # last digit of the number if number is odd
enterNum = enterNum / 10 # shift decimal places and remove the digit position
if digit % 2 == 1:
OUTPUT = POSITION * digit # if digit is odd, add it to the position
else:
continue
print(OUTPUT)
I am quite lost on what to do. When the number is 123407, I can only go up to printing 7. I do not know how to store the number in the data type and combine the digits in the end to get 137. Furthermore, I have a hard time looping through the number. It just gives me 7.
CodePudding user response:
Here is my approach:
num = 123407
res, power = 0, 1
while num:
last_digit = num % 10
if last_digit % 2 == 1:
res = last_digit * power
power *= 10
num = num // 10
print(res)
# 137
CodePudding user response:
Tested it out. Starting with your approach and just making a few modifications (see comments for details on modifications):
POSITION=0 # This starts at 0, this is because the power of 10 is 0 based (position 0 is the 1's place of the answer)
OUTPUT=0
enterNum= int(input('Enter a Number'))
while enterNum!=0:
digit=enterNum
enterNum=enterNum/10 #This will work for python2 I think, but in python3 you will need enterNum//10
if digit%2==1:
OUTPUT =(digit * 10**POSITION) # The digit needs to go in the current place value, if it is the 3rd digit, it needs to be multiplied by 100 (or 10^2).
POSITION = 1 # Add 1 to the position since we found one (need to place the next OUTPUT digit at the next position)
else:
continue
print(OUTPUT)
CodePudding user response:
Hint:
You obtain the digits of a number from right to left by the iterations
d = n % 10
n = n / 10
And you construct a number from right to left with:
n = d * p
p*= 10
(p = 1 initially.)
Now combine the two processes to transfer the odd digits.
