對于這項任務,我的任務是:
- 輸入一個數字
- 從給定數字中洗掉偶數而不更改數字的順序
例如:123407 將列印 137
如果一個數字以 246 開頭,則列印 0。
我不允許使用字串、串列、函式、包、遞回……,只能使用數學運算。
到目前為止,這是我的代碼:
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)
我完全不知道該怎么做。當數字是123407時,我最多只能列印7。我不知道如何將數字存盤在資料型別中并最終組合數字得到137。此外,我很難回圈數字. 它只給了我7。
uj5u.com熱心網友回復:
這是我的方法:
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
uj5u.com熱心網友回復:
測驗了它。從您的方法開始并進行一些修改(有關修改的詳細資訊,請參閱評論):
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)
uj5u.com熱心網友回復:
暗示:
您通過迭代從右到左獲得數字的數字
d = n % 10
n = n / 10
然后你從右到左構造一個數字:
n = d * p
p*= 10
(p = 1最初。)
現在結合這兩個程序來傳輸奇數位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421561.html
標籤:
下一篇:以編程方式減去SVG路徑
