ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Sum of Digits

Visual Basic .NET

Goal -- WPM

Ready
Exercise Algorithm Area
1Public Module DigitSumModule
2
3' Calculates the sum of the digits of a non-negative integer.
4Public Function SumOfDigits(ByVal n As Integer) As Integer
5' Ensure the input is non-negative.
6If n < 0 Then
7Throw New ArgumentOutOfRangeException(NameOf(n), "Input must be a non-negative integer.")
8End If
9
10Dim sum As Integer = 0
11Dim currentNumber As Integer = n
12
13' Loop until the number becomes zero.
14While currentNumber > 0
15' Get the last digit using the modulo operator.
16Dim digit As Integer = currentNumber Mod 10
17' Add the digit to the sum.
18sum += digit
19' Remove the last digit by integer division.
20currentNumber \\= 10
21End While
22
23' If the original number was 0, the loop won't execute, so sum will be 0, which is correct.
24Return sum
25End Function
26
27End Module
Algorithm description viewbox

Sum of Digits

Algorithm description:

This function computes the sum of all digits in a given non-negative integer. For example, the sum of digits for 123 is 1 + 2 + 3 = 6. This is a fundamental operation used in various number theory problems, checksum calculations, and data validation routines.

Algorithm explanation:

The `SumOfDigits` function iteratively extracts the last digit of a number and adds it to a running sum. The modulo operator (`Mod 10`) retrieves the last digit, and integer division (`\\ 10`) effectively removes it. This process continues until the number becomes zero. The loop invariant is that `sum` holds the sum of digits processed so far, and `currentNumber` holds the remaining part of the original number. The time complexity is O(d), where d is the number of digits in the input integer, which is logarithmic with respect to the value of the integer (O(log n)). The space complexity is O(1) as it uses a fixed amount of extra memory. The function correctly handles the edge case of `n = 0` as the `While` loop condition `currentNumber > 0` will be false, and it will return the initialized `sum` of 0.

Pseudocode:

Function SumOfDigits(number):
  If number is negative, throw error.
  Initialize sum = 0.
  While number > 0:
    digit = number modulo 10.
    Add digit to sum.
    Divide number by 10 (integer division).
  Return sum.