将整数中的奇数位相加

时间:2018-03-27 01:31:38

标签: python function loops sum

下面是我添加整数的奇数位时的尝试:

def sumOdd(n):
    for i in range(n):
        if n % 2 == 0:  # if n is odd
            n -= 1
    print(sum(range(1, n, 2)) + n)  # The range(1,n,2) starts at 1 and counts by twos until it reaches n


sumOdd(123)  # 4

任何提示?

4 个答案:

答案 0 :(得分:1)

如下:

代码:

def sum_odd_digits(number):
    return sum(int(d) for d in str(number) if d in '13579')

测试代码:

print(sum_odd_digits(123))
print(sum_odd_digits(133))

结果:

4
7

答案 1 :(得分:0)

两个解决方案,一个是将其转换为字符串,另一个是直接将其作为整数处理。

def sumOdd(n):
    n = str(n)
    sumn = 0
    for i in n:
        i = int(i)
        if i % 2 == 1:  # if n is odd
            sumn+=i
    return sumn

print(sumOdd(132495)) # 4388797504


def sumOdd_(n):
    n = abs(n)
    sumn = 0
    while n>0:
        digit = n%10
        n = n//10
        if digit %2 ==1:
            sumn+=digit
    return sumn

myn = 132495
assert sumOdd_(myn)==sumOdd(myn)

否则,您可以在Python中使用pythonic方式使用divmod。请注意,通常div和mode的运行速度比转换为str要快。

def sumOdd_2(n):
    sumn=0
    while n:
        # "pop" the rightmost digit
        n, digit = divmod(n, 10)
        if digit %2 ==1:
            sumn+=digit
    return sumn

答案 2 :(得分:0)

你也可以试试这个:

预处理数据:

data=123456789

real_data=list(map(int,str(data)))

对已处理数据的操作:

print(sum(filter(lambda x:x%2,real_data)))

print(functools.reduce(lambda x,y:x+y,(filter(lambda x:x%2,real_data))))

输出:

25

答案 3 :(得分:0)

<pre>
def check_odd(a):
    if a % 2 == 1:
        return True
    else:
        return False

def extract_last_digit(a):
    return a % 10

def remove_last_digit(a):
    return a // 10
 
x = input('Type an integer: ')

n = int(x)      

if n < 0:       # the integer may be negative (alternatively use n = abs(int(x)) in previous line)
    n = -1*n

sum_odd_n = 0

while n != 0:   
    if check_odd(n) == True:
        sum_odd_n += extract_last_digit(n)
    n = remove_last_digit(n)

print('The sum of the odd digits in number ', x, ' is ', str(sum_odd_n))
</pre>