To solve this problem, we can use the modulo operator (%
) and integer division (//
) to separate the digits of the two-digit integer.
Here’s some example code that demonstrates how to do this in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def sum_of_digits(n): # separate the tens digit and the ones digit tens = n // 10 ones = n % 10 # add the digits and return the result return tens + ones # test the function print(sum_of_digits(12)) # prints 3 print(sum_of_digits(23)) # prints 5 print(sum_of_digits(34)) # prints 7 |
This code first uses integer division (//
) to separate the tens digit and the ones digit of the input number n
. It then adds these digits together and returns the result.
Here’s an alternative way to solve this problem using string manipulation:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def sum_of_digits(n): # convert the integer to a string n = str(n) # add the digits and return the result return int(n[0]) + int(n[1]) # test the function print(sum_of_digits(12)) # prints 3 print(sum_of_digits(23)) # prints 5 print(sum_of_digits(34)) # prints 7 |
This code first converts the integer n
to a string, and then adds the two digits by converting them back to integers and using the +
operator.
Both of these approaches should work to solve the problem. Which one you choose will depend on your personal preference and the constraints of your specific situation.
Add comment