DSA problem
Check if a String Contains Only Digits
Given a string s, check whether it contains only numeric digits (0-9).
Iterate through each character and check whether it falls in the range 0 to 9. If any character does not, return false immediately (early termination). This is basic input validation - validating form inputs, parsing configuration files, sanitizing API payloads. Built-in helpers exist (Character.isDigit() in Java, str.isdigit() in Python, regex /^\d+$/ in JavaScript), but implementing it manually shows you understand character comparison and ASCII values. Digits 0 through 9 are contiguous in ASCII (48-57), so c >= '0' && c <= '9' works universally.
Examples
Example 1
Input:
s = "123456"Output:
trueExplanation: Every character is a digit between 0 and 9.
Example 2
Input:
s = "123a56"Output:
falseExplanation: The character a is not a digit, so the check fails.
Constraints
- 0 <= s.length <= 10^5
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.