Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove even digits from a number with only numerical operations, no list or strings

For this assignment, I am tasked to:

  1. Input a number
  2. 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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%10
    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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading