Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Sum 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.
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.
 
Solution

Buy us a coffee!

Back
Top Bottom