AlgoInsight

DSA problem

Count Digits in a Number

EasyMathPattern: MathbeginnerFree

Given an integer N, count how many digits it contains.

There are three common approaches. The loop approach repeatedly divides by 10 until the number reaches 0, counting iterations. The mathematical approach computes floor(log10(|N|)) + 1 directly in O(1). The string approach converts the number to text and returns its length.

Each method teaches something: the loop reinforces digit-extraction mechanics, the logarithm shows the power of a mathematical shortcut, and the string version is a reminder that the simplest code is sometimes the best. Remember to treat 0 as having one digit and to take the absolute value for negatives.

Examples

Example 1
Input: N = 123456
Output: 6
Explanation: 123456 contains 6 digits.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

math

Browse all DSA problems