Sum of Digits Calculator for Integers

  • Share this:

Code introduction


Calculate the sum of digits of an integer


Technology Stack : Built-in functions (isinstance, raise, //, %, if)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def sum_of_digits(n):
    if not isinstance(n, int):
        raise ValueError("Input must be an integer")
    if n < 0:
        return -sum_of_digits(-n)
    return n if n < 10 else sum_of_digits(n // 10) + n % 10