Tutorialspoint
Problem
Solution
Submissions

Sum of Digits of a Number

Certification: Basic Level Accuracy: 57.14% Submissions: 7 Points: 5

Write a C# program to implement the DigitSum(int number) function, which calculates the sum of all individual digits in a given integer number.

Algorithm
  • Step 1: If the number is negative, convert it to positive (use its absolute value).
  • Step 2: Iteratively extract each digit from the number using modulo and division operations.
  • Step 3: Add each extracted digit to a running total.
  • Step 4: Return the final sum of all digits.
Example 1
  • Input: number = 12345
  • Output: 15
  • Explanation:
    • The digits of 12345 are 1, 2, 3, 4, and 5.
    • 1 + 2 + 3 + 4 + 5 = 15
Example 2
  • Input: number = -789
  • Output: 24
  • Explanation:
    • First, we take the absolute value: 789
    • The digits of 789 are 7, 8, and 9.
    • 7 + 8 + 9 = 24
Constraints
  • -2^31 ≤ number ≤ 2^31 - 1
  • The input may be positive or negative.
  • Time Complexity: O(log n) where n is the number of digits
  • Space Complexity: O(1)
NumberFunctions / MethodsTech MahindraShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the modulo operator (%) to extract the last digit of the number.
  • Use integer division to remove the last digit after processing.
  • Repeat until the number becomes zero.
  • Handle negative numbers by taking the absolute value.


Submitted Code :