AlgoInsight

DSA problem

Check if a String Contains Only Digits

EasyStringsPattern: String TraversalbeginnerFree

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: true
Explanation: Every character is a digit between 0 and 9.
Example 2
Input: s = "123a56"
Output: false
Explanation: The character a is not a digit, so the check fails.

Constraints

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

stringvalidation

Browse all DSA problems