# PythonSum of Digits

#### austin

##### New Coder
I am working on writing a code named sumDigits which takes three parameters: a, b, c.

Then the function finds the smallest integer between a and b (both inclusive)

whose sum of digits is c, and returns that integer. For example,

sumDigits(10, 20, 5) will return 14, because the smallest integer between 10 and 20

whose sum of digits is 5, is 14 (1+4=5).

If there isn't an integer like this it should return -1.

def sumDigits(f, t, x):
>sum = 0
>for i in range(f, t+1):
>>if i > 0:
>>>Digits = i%10
>>>sum = sum + Digits
>>>i = i//10
>>>return sum
>>else:
>>>return -1

I tried someting like this but it doesn't work. What am I doing wrong?

Solution
Hi austin,

Next time, please use the </> button when you post code (And specify the language).

The following function should have the behavior you described:

Python:
``````def sumDigits(f, t, x):
sum = 0
for i in range(f, t+1):
sum = 0
num = i
while not num == 0:
sum += num % 10
num //= 10
if sum == x:
return i
return -1``````

It works with integers of any lenght.

#### LTomy

##### Active Coder
Staff Team
Guardian
Hi austin,

Next time, please use the </> button when you post code (And specify the language).

The following function should have the behavior you described:

Python:
``````def sumDigits(f, t, x):
sum = 0
for i in range(f, t+1):
sum = 0
num = i
while not num == 0:
sum += num % 10
num //= 10
if sum == x:
return i
return -1``````

It works with integers of any lenght.