Sum of Digits Calculator for Non-negative Integers

  • Share this:

Code introduction


Calculates the sum of all digits of a non-negative integer.


Technology Stack : Built-in functions (str(), int(), sum(), for loop)

Code Type : Function

Code Difficulty :


                
                    
def sum_of_digits(n):
    if not isinstance(n, int) or n < 0:
        return "Invalid input. Please provide a non-negative integer."
    return sum(int(digit) for digit in str(n))