DSA problem
Count Digits in a Number
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
N = 1234566Constraints
- -10^9 <= N <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.