FLOW006 - Editorial

Problem Link - Sum of Digits Practice Problem in Basic Math

Problem Statement:

You’re given an integer N . Write a program to calculate the sum of all the digits of N.

Approach:

For Calculating the sum of digits, we have to extract each digit from the number and then add them up.
Steps:

  • Initialize a variable to store the sum of digits (let’s call it sum).
  • Use a loop to repeatedly extract the last digit of N using the modulus operator (% 10), add this digit to sum, and then remove the last digit by dividing N by 10 (N = N/10).
  • Continue this process until N becomes 0.

Complexity:

  • Time Complexity: The time complexity for calculating the sum of digits for a single number N is O(d), where d is the number of digits in N. In the worst case, since N≤1,000,000, d can be at most 7.
  • Space Complexity: O(1) No extra space is required