Check if a String Contains Only Digits

Problem

Check whether a string contains only digit characters (0-9).

Input:  s = "12345"
Output: true

Input:  s = "12a45"
Output: false

Python Solution

def is_all_digits(s):
    return s.isdigit()

C++ Solution

bool isAllDigits(string s) {
    for (char ch : s) {
        if (!isdigit(ch)) return false;
    }
    return !s.empty();
}

Java Solution

class Solution {
    public boolean isAllDigits(String s) {
        if (s.isEmpty()) return false;
        for (char ch : s.toCharArray()) {
            if (!Character.isDigit(ch)) return false;
        }
        return true;
    }
}

Complexity

Time: O(n) — every character is checked once, returning early on the first non-digit. Space: O(1) — no extra structure used.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.