
Problem
Solution
Submissions
String Contains Only Digits
Certification: Basic Level
Accuracy: 100%
Submissions: 2
Points: 5
Write a C# program to check if a given string contains only digits (0-9). The function should return "true" if the string contains only digits and "false" otherwise. An empty string should return "false".
Example 1
- Input: str = "123456"
- Output: true
- Explanation:
- Step 1: Check if the string is null or empty (it's not).
- Step 2: Iterate through each character in the string "123456".
- Step 3: Check if each character is a digit between '0' and '9' inclusive.
- Step 4: All characters ('1', '2', '3', '4', '5', '6') are digits.
- Step 5: Return true since all characters in the string are digits.
Example 2
- Input: str = "12a34"
- Output: false
- Explanation:
- Step 1: Check if the string is null or empty (it's not).
- Step 2: Iterate through each character in the string "12a34".
- Step 3: Check if each character is a digit between '0' and '9' inclusive.
- Step 4: The character 'a' at index 2 is not a digit.
- Step 5: Return false immediately since not all characters in the string are digits.
Constraints
- 0 ≤ str.length ≤ 10⁴
- str consists of ASCII characters
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Check each character of the string to determine if it's a digit
- Use built-in C# functions to simplify the solution
- Handle edge cases like empty strings
- Consider using character code comparisons or regex for alternative solutions
- Return false as soon as a non-digit character is found for optimization