ScripticXLearn programming visually
Platform
Problems
Community
Leaderboard
Learn
Docs
MiniScript+ basicsVariablesOperators and expressionsInput and outputConditions and decisionsLoopsStringsSums, counts, and extremaDigits of a numberDivisibility and prime numbersNumeric sequences and recurrencesNumber basesFunctions and parametersRecursion
Examples
Basic programsConditionsInput and outputLoopsAlgorithmsWorking with textDigit problemsBase conversionsFunctions and recursionEncode text with a key
What's newHelpContact
Loading…

Documentation

MiniScript+

DocumentationMiniScript+
Getting started
MiniScript+ basics
Language basics
VariablesOperators and expressionsInput and outputConditions and decisionsLoopsStrings
Elementary algorithms
Sums, counts, and extremaDigits of a numberDivisibility and prime numbersNumeric sequences and recurrencesNumber bases
Functions
Functions and parametersRecursion
Documentation/Digits of a number

Digits of a number

Extract digits, calculate their sum, and reverse a non-negative integer.

On this page
Sum of digitsReverse a numberDigit count and edge casesPractice

For a non-negative integer, the last decimal digit is the remainder on division by 10. Integer division by 10 removes that digit. Repeating these operations visits digits from right to left. Review DIV and MOD first.

Sum of digits#

MS+MiniScript+
1n = 40722x = n3sum = 04WHILE x > 05  digit = x MOD 106  sum = sum + digit7  x = x DIV 108END9PRINT sum10PRINT n
x beforeExtracted digitSum afterx after
407222407
4077940
40094
44130

The output is 13, then 4072. The algorithm consumes the copy x, preserving n. When n = 0, the loop never runs, but the initial sum 0 is already correct.

Reverse a number#

Append a digit to the right by multiplying the current result by 10 and adding that digit.

MS+MiniScript+
1n = 12042x = n3reversed = 04WHILE x > 05  reversed = reversed * 10 + x MOD 106  x = x DIV 107END8PRINT reversed

The result is 4021. Reversing 1200 gives the number 21: numbers do not preserve leading zeros. If zeros belong to an identifier, use a string.

Digit count and edge cases#

Start a counter at zero and increment it whenever you remove a digit. Handle n = 0 separately: its decimal representation contains one digit, though WHILE x > 0 runs zero times. For negatives, decide whether to process ABS(n); a minus sign is not a digit.

Every step removes a digit, so k digits take O(k) steps. Keep calculations within the language's exact integer range; a reversed number may be larger than its input.

Practice#

  1. Count even digits in 4072: there are 3, including zero.
  2. Test whether a number equals its reversal; try 0, 7, 1221, 120.
  3. Find the product of the digits of 205: it is 0, not 10.
PreviousSums, counts, and extremaNextDivisibility and prime numbers

On this page

Sum of digitsReverse a numberDigit count and edge casesPractice