Codepath

Sum Of Digits

"TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Arithmetic, Iteration

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function sum_of_digits() should take an integer num and return the sum of its digits.
HAPPY CASE
Input: 423
Expected Output: 9

Input: 4
Expected Output: 4

EDGE CASE
Input: 0
Expected Output: 0

Input: 1001
Expected Output: 2

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define a function that iteratively extracts each digit of the number using modulus and floor division, summing the digits until the number is reduced to zero.

1. Define the function `sum_of_digits(num)`.
2. Initialize a variable `total_sum` to store the sum of the digits.
3. Use a while loop to iterate as long as `num` is greater than zero.
4. Within the loop:
   a. Add the last digit of `num` to `total_sum` using `num % 10`.
   b. Remove the last digit of `num` using floor division `num //= 10`.
5. Return `total_sum`

⚠️ Common Mistakes

  • Forgetting to handle the case where the input number is zero.
  • Incorrectly updating the number to remove the last digit.

I-mplement

Implement the code to solve the algorithm.

def sum_of_digits(num):
    total_sum = 0
    while num > 0:
        total_sum += num % 10  # Add the last digit to the sum
        num //= 10             # Remove the last digit
    return total_sum
Fork me on GitHub