通过递归只获取数字中的奇数位 [英] getting only the odd digits in a number with recursion
问题描述
所以我的问题是我有一个像 123 这样的数字,并且根据倾斜度,我希望结果是 13.
问题是,首先使用 im 的方法将得到取反结果(例如 31),其次我在末尾得到一个不应该存在的零,而不是将数字相加,而不是将它们和我不明白为什么.顺便说一句,我不能使用字符串
澄清一下:
我的输出:
<预><代码>>>>apenas_digitos_impares(123)40正确的输出:
<预><代码>>>>apenas_digitos_impares(123)13程序:
def apenas_digitos_impares(n):如果 n == 0:返回 0elif (n%10)%2 == 0:return apenas_digitos_impares(n//10)elif (n%10)%2 == 1:返回 10*(n%10) + apenas_digitos_impares(n//10)
你可以这样做 -
def apenas_digitos_impares(n):如果 n == 0:返回 0elif (n%10)%2 == 0:return apenas_digitos_impares(n//10)elif (n%10)%2 == 1:# 包括数字并递归剩余...返回 (n%10) + 10*apenas_digitos_impares(n//10)打印(apenas_digitos_impares(123))
输出:
13
您的代码所需的唯一更改是在函数的最后一行.
您将只包括奇数(由
n%10
完成)和,继续(或递归)检查剩余的数字.你需要将下一个数字乘以 10,所以 -
10*apenas_digitos_impares(n//10)
So my problem is this i have an number like 123 and as the tilte sugests i want the result to be 13.
The problem is that firstly with the method im using im going to get the invert result (31 for example), secondly im getting a zero at the end that shouldn't be there and instead of joining the digits its summing them and i dont understand why. BTW i cant use strings
So to clarify:
My output:
>>> apenas_digitos_impares(123)
40
Correct output:
>>> apenas_digitos_impares(123)
13
program:
def apenas_digitos_impares(n):
if n == 0:
return 0
elif (n%10)%2 == 0:
return apenas_digitos_impares(n//10)
elif (n%10)%2 == 1:
return 10*(n%10) + apenas_digitos_impares(n//10)
You could do it as follows -
def apenas_digitos_impares(n):
if n == 0:
return 0
elif (n%10)%2 == 0:
return apenas_digitos_impares(n//10)
elif (n%10)%2 == 1:
# Include the digit and recurse for remaining...
return (n%10) + 10*apenas_digitos_impares(n//10)
print(apenas_digitos_impares(123))
OUTPUT :
13
The only change that your code needed was in the last line of the function.
You will just include the odd digit(done by
n%10
) and,move on(or recurse) to check for remaining digits. You need to multiply next digit by 10, so -
10*apenas_digitos_impares(n//10)
这篇关于通过递归只获取数字中的奇数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!