203k views
1 vote
sum_even Write a program that reads an integer 0 < n < 2^32, returns the sum of all digits in n that are divisible by 2. For example, if n = 341238 the output would be 14, because it is the sum of 4 + 2 + 8. Hint: a signed int may not be enough.

1 Answer

2 votes

Answer:

Written in Python

n = int(input("Num: "))

sum_even = 0

if n > 0 and n < 2**32:

strn = str(n)

for i in range(0,len(strn)):

if int(strn[i])%2 == 0:

sum_even = sum_even+ int(strn[i])

print(sum_even)

Step-by-step explanation:

This line prompt user for input

n = int(input("Num: "))

This line initializes sum_even to 0

sum_even = 0

This line checks for valid input

if n > 0 and n < 2**32:

This line converts input to string

strn = str(n)

This line iterates through each digit of the input

for i in range(0,len(strn)):

This if condition checks for even number

if int(strn[i])%2 == 0:

This adds the even numbers

sum_even = sum_even+ int(strn[i])

This prints the sum of all even number in the user input

print(sum_even)

User Asif Shahzad
by
7.0k points